Reputation: 11
This is my code of custom hook from where i am returning the location of the device and asking the permission.This is a simple implementation but it is giving error
import * as Location from "expo-location";
import { useEffect, useState } from "react";
export default useLocation = () => {
const [location, setLocation] = useState();
const getLocation = async () => {
try {
const { granted } = await Location.requestForegroundPermissionsAsync();
if (granted) {
const { coords } = await Location.getLastKnownPositionAsync();
const { latitude, longitude } = coords;
setLocation({ latitude, longitude });
} else {
return;
}
} catch (error) {
console.log(error);
}
};
useEffect(() => {
getLocation();
}, []);
return location;
};
I am using the function by importing it like this
import useLocation from "../hooks/useLocation";
And soring the value like this
const location = useLocation()
It is giving error of null is not an object (evaluating '_await$Location$getLa.coords')
Upvotes: 1
Views: 1099
Reputation: 13289
I think that the problem is related to the fact that the getLastKnownPositionAsync()
function is returning null on some occasions.
This happens when the last position is not available or doesn't match certain requirements, as specified in the documentation
When this function is returning null, you can't destructure its result by using const { coords } = await Location.getLastKnownPositionAsync();
.
Adding a null check should resolve the problem.
import * as Location from "expo-location";
import { useEffect, useState } from "react";
export default useLocation = () => {
const [location, setLocation] = useState();
const getLocation = async () => {
try {
const { granted } = await Location.requestForegroundPermissionsAsync();
if (granted) {
/* Change the code below this comment */
const lastKnownPosition = await Location.getLastKnownPositionAsync();
if (!lastKnownPosition) {
return;
}
const { latitude, longitude } = lastKnownPosition.coords;
setLocation({ latitude, longitude });
} else {
return;
}
} catch (error) {
console.log(error);
}
};
useEffect(() => {
getLocation();
}, []);
return location;
};
Upvotes: 1