T
TanStack•10mo ago
correct-apricot

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
equal-aqua
equal-aqua•10mo ago
const data = await queryClient.fetchQuery(...)
correct-apricot
correct-apricotOP•10mo ago
Inside the handler, right? @TkDodo 🔮
equal-aqua
equal-aqua•10mo ago
Yes
correct-apricot
correct-apricotOP•10mo ago
Thanks!

Did you find this page helpful?