Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
React SetState within a async function

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!