about summary refs log tree commit diff
path: root/src/state/geolocation/useSyncedDeviceGeolocation.ts
blob: 602f29a30d3ff09d151738b0f31452230d83c4c6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import {useEffect, useRef} from 'react'
import * as Location from 'expo-location'

import {logger} from '#/state/geolocation/logger'
import {getDeviceGeolocation} from '#/state/geolocation/util'
import {device, useStorage} from '#/storage'

/**
 * Hook to get and sync the device geolocation from the device GPS and store it
 * using device storage. If permissions are not granted, it will clear any cached
 * storage value.
 */
export function useSyncedDeviceGeolocation() {
  const synced = useRef(false)
  const [status] = Location.useForegroundPermissions()
  const [deviceGeolocation, setDeviceGeolocation] = useStorage(device, [
    'deviceGeolocation',
  ])

  useEffect(() => {
    async function get() {
      // no need to set this more than once per session
      if (synced.current) return

      logger.debug('useSyncedDeviceGeolocation: checking perms')

      if (status?.granted) {
        const location = await getDeviceGeolocation()
        if (location) {
          logger.debug('useSyncedDeviceGeolocation: syncing location')
          setDeviceGeolocation(location)
          synced.current = true
        }
      } else {
        const hasCachedValue = device.get(['deviceGeolocation']) !== undefined

        /**
         * If we have a cached value, but user has revoked permissions,
         * quietly (will take effect lazily) clear this out.
         */
        if (hasCachedValue) {
          logger.debug(
            'useSyncedDeviceGeolocation: clearing cached location, perms revoked',
          )
          device.set(['deviceGeolocation'], undefined)
        }
      }
    }

    get().catch(e => {
      logger.error('useSyncedDeviceGeolocation: failed to sync', {
        safeMessage: e,
      })
    })
  }, [status, setDeviceGeolocation])

  return [deviceGeolocation, setDeviceGeolocation] as const
}