-1

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

}

1 Answers1

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});
daniel
  • 76
  • 3
  • it was a bit typo) setForecast({ currentDay, currentDayDetails}) it was before I tried to use callback but it didnt work too – lisovskiy329 Nov 20 '21 at 20:05