I am trying to use geolocation in my react app.
i am getting the latitude and longitude in the console, but I am getting the error:
Unhandled Rejection (TypeError): Cannot read property 'coords' of undefined.
here's my code:
const [location, setLocation]= useState({
coordinates: {lat:"", long:""}
});
const onSucces = location=>{
setLocation({
coordinates:{
lat: location.coords.latitude,
long: location.coords.longitude
}
})
};
useEffect(()=>{
if (!("geolocation" in navigator)){
console.log("Geolocation is not supported")
}
navigator.geolocation.getCurrentPosition(onSucces)
}, []);
console.log(location)
const getTeamLeadersLocation = async () => {
const result = await client.post('api/team/location',
{
"Location":{
"coords":{
"latitude":location.coordinates.lat,
"longitude":location.coordinates.long,
}
}
}
)
if(!result.ok){
console.log(result, result.originalError, result.problem, result.status);
return;
}
onSucces()
console.log(result)
}
useEffect(() => {
getTeamLeadersLocation();
}, []);
please help.
In your getTeamLeadersLocation()
function you are calling onSuccess
without the required location
parameter. So it tries to access coords
of undefined. Hence you get the error. Also, you already called your state location
and this variable can get shadowed, so you should rename one of them. This makes it also less confusing to debug.