Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!