After I fetched data from an api I am trying to update a state, but it is not updating.
I am also getting the response successfully.
I have also added the calling function.
Here is the function and state :
const getWeather = async (lat, lon) => {
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey.apiKey}`;
const data = await fetch(url);
const response = await data.json();
console.log(response);
console.log(response.main.temp);
setWeather({
lat: lat,
lon: lon,
temperature: Math.round(response.main.temp),
feelstemp: Math.round(response.main.feels_like),
desc: response.weather.description,
humidity: response.main.humidity,
pressure: response.main.pressure,
visibility: response.visibilty,
windspeed: response.wind.speed,
sunrise: response.sys.sunrise,
sunset: response.sys.sunset,
city: response.city,
country: response.sys.country,
main: response.weather[0].main,
});
console.log(weather);
};
//Calling function in another file.
useEffect(() => {
if (navigator.geolocation) {
getLocation()
//If user allow location service then will fetch data & send it to get-weather function.
.then((position) => {
getWeather(position.coords.latitude, position.coords.longitude);
})
.catch((err) => {
//If user denied location service then standard location weather will le shown on basis of latitude & latitude.
getWeather(28.67, 77.22);
alert(
"You have disabled location service. Allow 'This APP' to access your location. Your current location will be used for calculating Real time weather."
);
});
} else {
alert("Geolocation not available");
}
}, []);
Plese help me updating the state.
2
Answers
Your response is successfully received through API means the code is working. But since in your code
setWeather
is aasync
function, it is not called synchronously in the component and the log is not updating correctly. To log the output, you need to use auseEffect
hook like the following:This hook will detect the change in
setWeather
function whenever theweather
state gets updated and trigger the log.To learn more about
useEffect
hook, see official documentation here: https://beta.reactjs.org/reference/react/useEffectUpdate: I just noticed there is a spelling error of the value
visibility
in your response.data JSON object. I recommend you should double-check the API reference to make sure it is correct.You still need to execute your function, you only defined the function
getWeather
but you still need to call it. You can not just go ahead and callgetWeather
later on in the code because of possible rerenders it will get fetched every time. You need to useuseEffect
for this.But because you’re using
getWeather
in theuseEffect
you need to add it to the dependency array:But because
getWeather
is not a callback function you need to wrapgetWeather
withuseCallback