React Native
Gallery permission
Learn to ask for gallery permission.
Gallery permission
Picking an image from the gallery requires asking the user for permission. expo-image-picker offers requestMediaLibraryPermissionsAsync. This function returns an object; if the status field is 'granted' the gallery 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 the gallery button stays disabled.
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 gallery button. While state is null the button stays disabled. This pattern gives meaningful feedback in every case.
Exercise Request permission and write to state
Complete the empty useEffect. Call const permission = await ImagePicker.requestMediaLibraryPermissionsAsync(); write the result with setHasPermission(permission.status === 'granted'). The second argument of useEffect should be [].
Show example solution
(async () => {
const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
setHasPermission(permission.status === 'granted');
})();
Test yourself
-
Write the permission function
const permission = await ImagePicker.____();
Show answer
const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
-
Which field of the permission object is checked for 'granted'?
if (permission.??? === 'granted') { ... }
- granted
- result
- allowed
- status
Show answer
status — The status field carries the 'granted' value.
-
Match each state value to its meaning
- null
- Waiting for permission
- true
- Gallery available
- false
- Permission denied
- 'granted'
- status value
Next lesson: launchImageLibraryAsync