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

104
Views
React function uses outdated state

I am using react-query to fetch external data, based on the current state here is how the code looks like

const Home = () => {
  const queryClient = useQueryClient();
  const [group, setGroup] = useState(1);

  const query = useQuery('/query', async () => {
    console.log(group);

    return axios.get('/query', { params: { group } });
  });

  useEffect(() => {
    queryClient.invalidateQueries('/query');
  }, [group, queryClient]);

  return (
    <div>
      <button onClick={() => setGroup(1)}>First group</button>
      <button onClick={() => setGroup(2)}>Second group</button>
    </div>
  );
};

There are 2 buttons that changes the state (group), and when the state changes (useEffect) I invalidate old queries to send new queries but the problem is that the callback has only the initial state and not the updated state and when it get executed it prints out the initial state

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think that you should modify your useQuery section in this way

const query = useQuery(['/query', group], async () => {
    console.log(group);

    return axios.get('/query', { params: { group } });
  });
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!