T
TanStack•13mo ago
conscious-sapphire

What's the best practice to refetch data on select change that triggers a mutate

Hey guys, I have a following situation and I'm getting nowhere with my limited knowledge of react-query. What happens is that currentActionName doesn't get updated in time for actionData to be updated/refetched so that updateBigData.mutate can be invoked with the fresh data (actionData belonging to newActionName) Here's an abbreviated version of my code:
// for example: currentActionName = "write", newActionName = "read"
component = () => {
const [currentActionName, setCurrentActionName] = useState('');

const {data: actionData} = useGetActionQuery({
actionName: currentActionName,
...
}); // this successfully returns actionData belonging to "write" action on render

const handleActionChange = (newActionName) => {
setCurrentActionName(newActionName); // because of how React works, the currentActionName is still "write" for the purpose of the rest of the block

updateBigData.mutate({
newActionData, // PROBLEM HERE: Sends actionData with the old currentActionName ("write"), not refetched actionData that belongs to newActionName ("read")
...
});
}

<Select onChange={handleActionChange} value={currentActionName} />
}
// for example: currentActionName = "write", newActionName = "read"
component = () => {
const [currentActionName, setCurrentActionName] = useState('');

const {data: actionData} = useGetActionQuery({
actionName: currentActionName,
...
}); // this successfully returns actionData belonging to "write" action on render

const handleActionChange = (newActionName) => {
setCurrentActionName(newActionName); // because of how React works, the currentActionName is still "write" for the purpose of the rest of the block

updateBigData.mutate({
newActionData, // PROBLEM HERE: Sends actionData with the old currentActionName ("write"), not refetched actionData that belongs to newActionName ("read")
...
});
}

<Select onChange={handleActionChange} value={currentActionName} />
}
I hope the code above describes it well, but what my question is, what's the best pattern in this case where I have a query that needs to be refetched inside an event handler so that the rest of the code inside the handler has access to the refetched code.
4 Replies
continuing-cyan
continuing-cyan•13mo ago
const data = await queryClient.fetchQuery(...)
conscious-sapphire
conscious-sapphireOP•13mo ago
Inside the handler, right? @TkDodo 🔮
continuing-cyan
continuing-cyan•13mo ago
Yes
conscious-sapphire
conscious-sapphireOP•13mo ago
Thanks!

Did you find this page helpful?