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

265
Views
Can we change state before making an API call which uses that state? React
 useEffect(() => {
    resetState();
    if (page === 'ADMISSION') {
      fetchAdmissionKitPosts();
    } else if (page === 'WEEKLY') {
      fetchWeeklyKitPosts();
    } else if (page === 'FESTIVAL') {
      fetchFestivalKitPosts();
    }
  }, [page]);

So I want to make different API calls based on the page variable. I have to reset the state before making those calls. But while making the call I'm getting the previous state. I came to know that the setState in react is async in nature, so I assume that that's why I'm getting the previous state in the API call functions.

So my question is, how can I make it so that these API calls only run after the state has been reset?

I know that I can use a callback function in the class-based component with the setState function. But I want to keep this component functional.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can implement setState callback in functional component with useEffect. if i'm getting it right, you are using two state variables page and posts, if this is the case you should use two useEffect methods like this:

useEffect(() => {
   if(page !== ''){
    setMarketingPosts([])
   } 
  }, [page]);

  useEffect(() => {
    if (page === 'ADMISSION') {
      fetchAdmissionKitPosts();
    } else if (page === 'WEEKLY') {
      fetchWeeklyKitPosts();
    } else if (page === 'FESTIVAL') {
      fetchFestivalKitPosts();
    }
    setNextPageToken('')
  }, [post]);
about 4 years ago · Santiago Trujillo 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!