I'm trying to learn React making a weather application and I have got stacked using the async/await function. Here is the trouble I'm facing..
I have a function which does a axios call to an api and then I'm trying to set some state variables. The think is that it seems the application is running the setState methods before the promise is resolved.
Here is the method that makes the axios call.
const fetchWeeklyWeather = async () => {
try {
let response = await axios.get(url);
console.log('%cFetch Weekly Weather Response:', 'color: #bada55', response);
setCurrentWeather(response.data.current);
setWeeklyWeather(response.data.daily);
setWeatherAlerts(response.data.alerts);
} catch (err) {
// Handle Error Here
console.error(err);
}
}
And I call that method on the componentDidMount like so:
useEffect(() => {
fetchWeeklyWeather();
console.log("Current Weather", currentWeather);
console.log("Weekly Weather", weeklyWeather);
console.log("Weather alerts", weatherAlerts);
formatData(weeklyWeather);
}, []);
It is weird because sometimes it works but most of the time it does not. I guess I'm not doing the right think with the async/await. Can anyone give me a hand?
Thank you so much!
Lots of discussion here React setState not Updating Immediately
But basically, setState is async/ a request to update state in the next render. Therefor, the updates to state are not immediately available/observable