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

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

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 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