Why does this ReactJS code call navigator.geolocation.getCurrentLocation infinitely? console.log in getCurrentLocation is called forever. Why is that?
const [today, setTodaysWeather] = useState('');
const [{lat, lng}, setLocation] = useState({lat: 0, lng: 0});
if(!navigator.geolocation) {
console.log("gelolocation is not supported by your browser");
}
else {
navigator.geolocation.getCurrentPosition((position) => {
setLocation({
lat: position.coords.latitude,
lng: position.coords.longitude
});console.log(lat);
},
(err) => {
console.log("Error getting location");
});
}
useEffect(() => {
fetch("//api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lng + "&appid=")
.then((response) => {
return response.json();
})
.then((json) => {
setTodaysWeather(json);
})
});
You should wrap this code in an effect, as that code is changing the state via setLocation
, that triggers another render, which runs your code again recursively.
useEffect(()=> {
if(!navigator.geolocation) {
console.log("gelolocation is not supported by your browser");
}
else {
navigator.geolocation.getCurrentPosition((position) => {
setLocation({
lat: position.coords.latitude,
lng: position.coords.longitude
});console.log(lat);
},
(err) => {
console.log("Error getting location");
});
}
}, [])
The empty array as the second argument to effect function will make sure this code is ran only once, during first render of the component.