Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda