|
| 1 | +import AsyncStorage from '@react-native-async-storage/async-storage'; |
| 2 | +import * as Location from 'expo-location'; |
| 3 | +import { useAtom, useAtomValue, useSetAtom } from 'jotai'; |
| 4 | +import { useEffect, useMemo, useRef } from 'react'; |
| 5 | +import { Alert } from 'react-native'; |
| 6 | +import type { Station } from '~/@types/graphql'; |
| 7 | +import { ASYNC_STORAGE_KEYS, LOCATION_TASK_NAME } from '../constants'; |
| 8 | +import { locationAtom, setLocation } from '../store/atoms/location'; |
| 9 | +import navigationState from '../store/atoms/navigation'; |
| 10 | +import stationState from '../store/atoms/station'; |
| 11 | +import { translate } from '../translation'; |
| 12 | +import { useFetchCurrentLocationOnce } from './useFetchCurrentLocationOnce'; |
| 13 | +import { useFetchNearbyStation } from './useFetchNearbyStation'; |
| 14 | + |
| 15 | +const INITIAL_LOCATION_FALLBACK_DELAY_MS = 800; |
| 16 | + |
| 17 | +export type UseInitialNearbyStationResult = { |
| 18 | + station: Station | null; |
| 19 | + nearbyStationLoading: boolean; |
| 20 | +}; |
| 21 | + |
| 22 | +export const useInitialNearbyStation = (): UseInitialNearbyStationResult => { |
| 23 | + const [stationAtomState, setStationState] = useAtom(stationState); |
| 24 | + const setNavigationState = useSetAtom(navigationState); |
| 25 | + const location = useAtomValue(locationAtom); |
| 26 | + const latitude = location?.coords.latitude; |
| 27 | + const longitude = location?.coords.longitude; |
| 28 | + |
| 29 | + const { station: stationFromAtom } = stationAtomState; |
| 30 | + const initialNearbyFetchInFlightRef = useRef(false); |
| 31 | + |
| 32 | + const { |
| 33 | + stations: nearbyStations, |
| 34 | + fetchByCoords, |
| 35 | + isLoading: nearbyStationLoading, |
| 36 | + error: nearbyStationFetchError, |
| 37 | + } = useFetchNearbyStation(); |
| 38 | + |
| 39 | + const { fetchCurrentLocation } = useFetchCurrentLocationOnce(); |
| 40 | + |
| 41 | + const station = useMemo( |
| 42 | + () => stationFromAtom ?? nearbyStations[0] ?? null, |
| 43 | + [stationFromAtom, nearbyStations] |
| 44 | + ); |
| 45 | + |
| 46 | + // バックグラウンド位置更新を停止 |
| 47 | + useEffect(() => { |
| 48 | + const stopLocationUpdates = async () => { |
| 49 | + const hasStartedLocationUpdates = |
| 50 | + await Location.hasStartedLocationUpdatesAsync(LOCATION_TASK_NAME); |
| 51 | + if (hasStartedLocationUpdates) { |
| 52 | + await Location.stopLocationUpdatesAsync(LOCATION_TASK_NAME); |
| 53 | + } |
| 54 | + }; |
| 55 | + stopLocationUpdates(); |
| 56 | + }, []); |
| 57 | + |
| 58 | + // 最寄り駅の取得 |
| 59 | + useEffect(() => { |
| 60 | + const fetchInitialNearbyStationAsync = async (coords?: { |
| 61 | + latitude: number; |
| 62 | + longitude: number; |
| 63 | + }) => { |
| 64 | + if (station || initialNearbyFetchInFlightRef.current) return; |
| 65 | + initialNearbyFetchInFlightRef.current = true; |
| 66 | + |
| 67 | + try { |
| 68 | + let requestCoords = coords; |
| 69 | + if (!requestCoords) { |
| 70 | + const currentLocation = await fetchCurrentLocation(true); |
| 71 | + if (!currentLocation) return; |
| 72 | + setLocation(currentLocation); |
| 73 | + requestCoords = { |
| 74 | + latitude: currentLocation.coords.latitude, |
| 75 | + longitude: currentLocation.coords.longitude, |
| 76 | + }; |
| 77 | + } |
| 78 | + |
| 79 | + const data = await fetchByCoords({ |
| 80 | + latitude: requestCoords.latitude, |
| 81 | + longitude: requestCoords.longitude, |
| 82 | + limit: 1, |
| 83 | + }); |
| 84 | + |
| 85 | + const stationFromAPI = data.data?.stationsNearby[0] ?? null; |
| 86 | + setStationState((prev) => ({ |
| 87 | + ...prev, |
| 88 | + station: stationFromAPI, |
| 89 | + })); |
| 90 | + setNavigationState((prev) => ({ |
| 91 | + ...prev, |
| 92 | + stationForHeader: stationFromAPI, |
| 93 | + })); |
| 94 | + } catch (error) { |
| 95 | + console.error(error); |
| 96 | + } finally { |
| 97 | + initialNearbyFetchInFlightRef.current = false; |
| 98 | + } |
| 99 | + }; |
| 100 | + |
| 101 | + if (latitude != null && longitude != null) { |
| 102 | + fetchInitialNearbyStationAsync({ latitude, longitude }); |
| 103 | + return; |
| 104 | + } |
| 105 | + |
| 106 | + const fallbackTimerId = setTimeout(() => { |
| 107 | + fetchInitialNearbyStationAsync(); |
| 108 | + }, INITIAL_LOCATION_FALLBACK_DELAY_MS); |
| 109 | + |
| 110 | + return () => { |
| 111 | + clearTimeout(fallbackTimerId); |
| 112 | + }; |
| 113 | + }, [ |
| 114 | + fetchByCoords, |
| 115 | + fetchCurrentLocation, |
| 116 | + latitude, |
| 117 | + longitude, |
| 118 | + setNavigationState, |
| 119 | + setStationState, |
| 120 | + station, |
| 121 | + ]); |
| 122 | + |
| 123 | + // 初回起動アラート |
| 124 | + useEffect(() => { |
| 125 | + const checkFirstLaunch = async () => { |
| 126 | + const firstLaunchPassed = await AsyncStorage.getItem( |
| 127 | + ASYNC_STORAGE_KEYS.FIRST_LAUNCH_PASSED |
| 128 | + ); |
| 129 | + if (firstLaunchPassed === null) { |
| 130 | + Alert.alert(translate('notice'), translate('firstAlertText'), [ |
| 131 | + { |
| 132 | + text: 'OK', |
| 133 | + onPress: (): void => { |
| 134 | + AsyncStorage.setItem( |
| 135 | + ASYNC_STORAGE_KEYS.FIRST_LAUNCH_PASSED, |
| 136 | + 'true' |
| 137 | + ); |
| 138 | + }, |
| 139 | + }, |
| 140 | + ]); |
| 141 | + } |
| 142 | + }; |
| 143 | + checkFirstLaunch(); |
| 144 | + }, []); |
| 145 | + |
| 146 | + // 最寄り駅取得エラーのアラート |
| 147 | + useEffect(() => { |
| 148 | + if (nearbyStationFetchError) { |
| 149 | + console.error(nearbyStationFetchError); |
| 150 | + Alert.alert(translate('errorTitle'), translate('apiErrorText')); |
| 151 | + } |
| 152 | + }, [nearbyStationFetchError]); |
| 153 | + |
| 154 | + return { station, nearbyStationLoading }; |
| 155 | +}; |
0 commit comments