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
CodePudding user response:
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 } });
});