Location permission
- React Native course
- Advanced
- Lesson 20/83
- 5 min
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.
Practice 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 [].
Starter code
import React from 'react';
import * as Location from 'expo-location';
export function useLocationPermission() {
const [hasPermission, setHasPermission] = React.useState(null);
React.useEffect(() => {
// request permission and write the result
}, []);
return hasPermission;
}Sample solution
(async () => {
const permission = await Location.requestForegroundPermissionsAsync();
setHasPermission(permission.status === 'granted');
})();Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the permission function
const permission = await Location.____();
const permission = await Location.requestForegroundPermissionsAsync();
Explanation: requestForegroundPermissionsAsync asks for location permission.
2 Which field carries the 'granted' value?
if (permission.??? === 'granted') { ... }- status Correct answer
- granted
- allowed
- result
Explanation: The status field carries the 'granted' value.
3 Match each state value to its meaning
| Term | Meaning |
|---|---|
null |
Waiting for permission |
true |
Location available |
false |
Permission denied |
'granted' |
status value |