Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda