Skip to content

Instantly share code, notes, and snippets.

@Grohden
Created November 26, 2024 13:28
Show Gist options
  • Save Grohden/44ed351476a049e5522b5a0ba789a143 to your computer and use it in GitHub Desktop.
Save Grohden/44ed351476a049e5522b5a0ba789a143 to your computer and use it in GitHub Desktop.
Hook to handle the permission flow of the react-native-permissions package
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