T
TanStack15mo ago
wise-white

`await queryClient.refetchQueries` resolves too early

I want to run a mutation that unfortunately has to be async, because it makes a new page that we want to navigate to ASAP. So currently, I await mutateAsync, and await queryClient.refetchQueries for the appropriate query key. However, the promise for refetchQueries resolves before the refetch is actually complete - why is that? The promise resolves while the refetch is not finished, and my page tries to redirect to a page that has no data yet (bad). Here is my sample code:
const newVersionId = await mutateAsync();
await queryClient.refetchQueries({
queryKey: ["projects", project.id],
});
const newVersionId = await mutateAsync();
await queryClient.refetchQueries({
queryKey: ["projects", project.id],
});
I know I'm using the right query key. I could hack together a solution by monitoring isFetching on the associated useQuery hook, but that seems janky and wrong.
5 Replies
conscious-sapphire
conscious-sapphire15mo ago
How do you know that refetch is not complete? Because the docs say that This function returns a promise that will resolve when all of the queries are done being refetched.
wise-white
wise-whiteOP15mo ago
Because if I monitor the useQuery.isFetching state, I can see that the promise returns before isFetching becomes false. Also the devtools show that it's still fetching. The difference is significant, at least a second, it's not a close call
conscious-sapphire
conscious-sapphire15mo ago
Isfetching also depends on this promise resolution or how do you think they calculate it? So obviously that promise will return first and isfetching may return after with a small delay. If it's not like seconds then this probably not a problem. Then we need a reproduction of your code, because now we are guessing
wise-white
wise-whiteOP15mo ago
I found a workaround, turns out if I add a brief delay between these calls, it behaves correctly. Maybe something about calling them too close together?
const newVersionId = await createNewVersionAsync();

await delay(100);

await queryClient.refetchQueries({
queryKey: ["projects", project.id],
});

return newVersionId;
const newVersionId = await createNewVersionAsync();

await delay(100);

await queryClient.refetchQueries({
queryKey: ["projects", project.id],
});

return newVersionId;
conscious-sapphire
conscious-sapphire15mo ago
Maybe it's just your BE that can not process this two calls so quick.

Did you find this page helpful?