React Native
Location permission
Learn to ask for location permission.
Location permission
Accessing location info requires asking the user for permission. The expo-location package offers Location.requestForegroundPermissionsAsync. This function returns an object; if the status field is 'granted' the location 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, location cannot be obtained; you show the user a reason.
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 start showing the location. This pattern gives the user meaningful feedback in every case. While state is null the location functions are not called.
Exercise Request permission and write to state
Complete the empty useEffect. Call const permission = await Location.requestForegroundPermissionsAsync(); write the result with setHasPermission(permission.status === 'granted'). The second argument of useEffect should be [].
Show example solution
(async () => {
const permission = await Location.requestForegroundPermissionsAsync();
setHasPermission(permission.status === 'granted');
})();
Test yourself
-
Write the permission function
const permission = await Location.____();
Show answer
const permission = await Location.requestForegroundPermissionsAsync();
-
Which field carries the 'granted' value?
if (permission.??? === 'granted') { ... }
- status
- granted
- allowed
- result
Show answer
status — The status field carries the 'granted' value.
-
Match each state value to its meaning
- null
- Waiting for permission
- true
- Location available
- false
- Permission denied
- 'granted'
- status value
Next lesson: getCurrentPositionAsync