Created
November 26, 2024 13:28
-
-
Save Grohden/44ed351476a049e5522b5a0ba789a143 to your computer and use it in GitHub Desktop.
Hook to handle the permission flow of the react-native-permissions package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Permission, RESULTS, check, request } from 'react-native-permissions'; | |
import { useCallback } from 'react'; | |
export const useRequestPermissionFlow = () => { | |
return useCallback( | |
async ( | |
permission: Permission, | |
callbacks: { | |
onFeatureUnavailable: () => Promise<void>; | |
onPermissionGranted: (type: 'limited' | 'granted') => Promise<void>; | |
onPermissionDenied: () => Promise<void>; | |
onPermissionBlocked: () => Promise<void>; | |
}, | |
) => { | |
const status = await check(permission); | |
if (status === RESULTS.GRANTED || status === RESULTS.LIMITED) { | |
return callbacks.onPermissionGranted(status); | |
} | |
if (status === RESULTS.BLOCKED) { | |
return callbacks.onPermissionBlocked(); | |
} | |
if (status === RESULTS.DENIED) { | |
const requestResult = await request(permission); | |
if ( | |
requestResult === RESULTS.GRANTED || | |
requestResult === RESULTS.LIMITED | |
) { | |
return callbacks.onPermissionGranted(requestResult); | |
} else { | |
return callbacks.onPermissionDenied(); | |
} | |
} | |
return callbacks.onFeatureUnavailable(); | |
}, | |
[], | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment