fix: Refresh Permissions on AppState change (#2420)

This commit is contained in:
Marc Rousavy 2024-01-19 12:17:04 +01:00 committed by GitHub
parent f400487a8d
commit 97684af851
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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<boolean>
}
function usePermission(get: () => CameraPermissionStatus, request: () => Promise<CameraPermissionRequestResult>): 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)
}