diff --git a/package/src/hooks/useCameraPermission.ts b/package/src/hooks/useCameraPermission.ts index 6309bc5..3d25497 100644 --- a/package/src/hooks/useCameraPermission.ts +++ b/package/src/hooks/useCameraPermission.ts @@ -1,5 +1,6 @@ -import { useCallback, useState } from 'react' -import { Camera } from '../Camera' +import { useCallback, useEffect, useState } from 'react' +import { Camera, CameraPermissionRequestResult, CameraPermissionStatus } from '../Camera' +import { AppState } from 'react-native' interface PermissionState { /** @@ -14,6 +15,30 @@ interface PermissionState { requestPermission: () => Promise } +function usePermission(get: () => CameraPermissionStatus, request: () => Promise): PermissionState { + const [hasPermission, setHasPermission] = useState(() => get() === 'granted') + + const requestPermission = useCallback(async () => { + const result = await request() + const hasPermissionNow = result === 'granted' + setHasPermission(hasPermissionNow) + return hasPermissionNow + }, [request]) + + useEffect(() => { + // Refresh permission when app state changes, as user might have allowed it in Settings + const listener = AppState.addEventListener('change', () => { + setHasPermission(get() === 'granted') + }) + return () => listener.remove() + }, [get]) + + return { + hasPermission, + requestPermission, + } +} + /** * Returns whether the user has granted permission to use the Camera, or not. * @@ -31,19 +56,7 @@ interface PermissionState { * ``` */ export function useCameraPermission(): PermissionState { - const [hasPermission, setHasPermission] = useState(() => Camera.getCameraPermissionStatus() === 'granted') - - const requestPermission = useCallback(async () => { - const result = await Camera.requestCameraPermission() - const hasPermissionNow = result === 'granted' - setHasPermission(hasPermissionNow) - return hasPermissionNow - }, []) - - return { - hasPermission, - requestPermission, - } + return usePermission(Camera.getCameraPermissionStatus, Camera.requestCameraPermission) } /** @@ -61,17 +74,5 @@ export function useCameraPermission(): PermissionState { * ``` */ export function useMicrophonePermission(): PermissionState { - const [hasPermission, setHasPermission] = useState(() => Camera.getMicrophonePermissionStatus() === 'granted') - - const requestPermission = useCallback(async () => { - const result = await Camera.requestMicrophonePermission() - const hasPermissionNow = result === 'granted' - setHasPermission(hasPermissionNow) - return hasPermissionNow - }, []) - - return { - hasPermission, - requestPermission, - } + return usePermission(Camera.getMicrophonePermissionStatus, Camera.requestMicrophonePermission) }