Skip to content

Instantly share code, notes, and snippets.

@jseed
Last active December 1, 2019 04:29
Show Gist options
  • Save jseed/d33a83ff5af16508f5e162ecfd184dca to your computer and use it in GitHub Desktop.
Save jseed/d33a83ff5af16508f5e162ecfd184dca to your computer and use it in GitHub Desktop.
react-native context camera permissions hook
// PermissionsContext.js
import React, { createContext, useState } from 'react';
const PermissionsContext = createContext();
function PermissionsProvider({ children }) {
const [hasCameraPermissions, setHasCameraPermissions] = useState(null);
return (
<PermissionsContext.Provider value={[hasCameraPermissions, setHasCameraPermissions]}>
{children}
</PermissionsContext.Provider>
);
}
export { PermissionsProvider, PermissionsContext };
// useCameraPermissions.js - custom hook
import { useContext, useEffect } from 'react';
import * as Permissions from 'expo-permissions';
import { PermissionsContext } from '../context/PermissionsContext';
export default function useCameraPermissions() {
const [hasCameraPermissions, setHasCameraPermissions] = useContext(PermissionsContext);
useEffect(() => {
Permissions.askAsync(Permissions.CAMERA).then(({ status }) =>
setHasCameraPermissions(status === 'granted'),
);
}, []);
return hasCameraPermissions;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment