'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
Solution 1:[1]
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 } });
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R4ncid |
