about summary refs log tree commit diff
path: root/src/state/geolocation/useRequestDeviceLocation.ts
blob: 64e05b056ad136ae1f843025ee3309f543814dc9 (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
import {useCallback} from 'react'
import * as Location from 'expo-location'

import {type DeviceLocation} from '#/state/geolocation/types'
import {getDeviceGeolocation} from '#/state/geolocation/util'

export {PermissionStatus} from 'expo-location'

export function useRequestDeviceLocation(): () => Promise<
  | {
      granted: true
      location: DeviceLocation | undefined
    }
  | {
      granted: false
      status: {
        canAskAgain: boolean
        /**
         * Enum, use `PermissionStatus` export for comparisons
         */
        permissionStatus: Location.PermissionStatus
      }
    }
> {
  return useCallback(async () => {
    const status = await Location.requestForegroundPermissionsAsync()

    if (status.granted) {
      return {
        granted: true,
        location: await getDeviceGeolocation(),
      }
    } else {
      return {
        granted: false,
        status: {
          canAskAgain: status.canAskAgain,
          permissionStatus: status.status,
        },
      }
    }
  }, [])
}