React Native
Camera permission
Learn to ask for camera permission.
Camera permission
To use the camera you must ask the user for permission. The expo-camera package offers Camera.requestCameraPermissionsAsync. This function returns an object; if the status field is 'granted' the camera is usable.
You make the permission request inside useEffect and write the result into state. State starts as null (not asked), then becomes true or false. This pattern is the most robust way to ask for permission when the app opens. If permission is denied you show a warning text instead of the camera.
Permission state
You keep the permission result in state: const [hasPermission, setHasPermission] = React.useState(null). The initial value null means 'not asked yet'. Inside useEffect you request the permission and write the result with setHasPermission(permission.status === 'granted').
During render you check three states: if null show 'Waiting for permission', if false show 'Permission needed', if true show the camera. This three-way check gives the user meaningful feedback in every case. While state is null the camera is not rendered; this prevents possible errors.
Exercise Request permission and write to state
Complete the empty useEffect. Call const permission = await Camera.requestCameraPermissionsAsync(); write the result with setHasPermission(permission.status === 'granted'). The second argument of useEffect should be [].
Show example solution
(async () => {
const permission = await Camera.requestCameraPermissionsAsync();
setHasPermission(permission.status === 'granted');
})();
Test yourself
-
Write the permission function
const permission = await Camera.____();
Show answer
const permission = await Camera.requestCameraPermissionsAsync();
-
Match each state value to its meaning
- null
- Waiting for permission
- true
- Camera available
- false
- Permission denied
- 'granted'
- status value
-
What is shown when hasPermission is null?
if (hasPermission === null) { ... }
- A blank screen
- The camera
- A 'waiting for permission' text
- A crash error
Show answer
A 'waiting for permission' text — When null, a 'waiting for permission' text is shown.
Next lesson: Taking pictures