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

134
Visualizações
Callback doesnt solve useState asynchronous

guys I'm working on weather app and I struggle with useState asynchronous. I've read on stackoverflow that it can be solved with callback in useState function. So I've tried it but nothing changed. The issue is that when I click on submit button, state must receive data from API but it doesnt make it and I'm getting null in my state. What is wrong and if u can pls help me according to my code. P.S missed some funcrtions that are not important

const useForecast = () => {
    const [forecast, setForecast] = useState(null);
       
    const gatherForecastData = async data => {
        const currentDay = await getCurrentDayForecast(data.consolidated_weather[0], data.title);
        const currentDayDetails = await getCurrentDayDetailedForecast(data.consolidated_weather[0]);
         
        await setForecast(() => {
          return { currentDay, currentDayDetails};
          });
        setLoading(false);
    };

    // MAIN FUNC AND TROUBLE IS HERE
    const submitRequest = async location => {
        setLoading(true);
        setError(false);

        const response = await getWoeid(location);
        if (!response?.woeid) return;

        const data = await getForecastData(response.woeid);
        if (!data) return;
        
        await gatherForecastData(data);
        console.log(data);
        // DATA SHOWS OK
        console.log(forecast);
        // SHOWS INITIAL STATE FOR THE FIRST SUBMIT
    };

}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

useState is syncronous, also, you should pass the values you want, in this case the object

{ currentDay, currentDayDetails}

, so these lines

        await setForecast(() => {
      return { currentDay, currentDayDetails};
      });

should be

        setForecast({ currentDay, currentDayDetails});
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