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

1 answer

  • answered 2022-05-04 10:09 R4ncid

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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum