T
TanStack10mo ago
rising-crimson

How to wait for onSuccess to resolve on a mutation before setting isPending to false

For the following mutation, isPending is false once the mutation is resolved, so it does not wait for onSuccess to resolve.
useMutation({
mutationFn: mutation,
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['posts'],
});
},
});
useMutation({
mutationFn: mutation,
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['posts'],
});
},
});
A workaround, which is not as elegant is to drop onSuccess and invalidate the queries in the mutation function.
const mutation = async () => {
const response = await PATCH(`/api/fooBar`);

await queryClient.invalidateQueries({
queryKey: ['posts'],
});

return response;
};

useMutation({
mutationFn: mutation,
});
const mutation = async () => {
const response = await PATCH(`/api/fooBar`);

await queryClient.invalidateQueries({
queryKey: ['posts'],
});

return response;
};

useMutation({
mutationFn: mutation,
});
I am wondering if there is a better way to achieve this? The problem is that after the mutation I navigate back to a page, where the changes are not reflected instantly since the revalidation is triggering a refetch in the background, and the content of the page updates after a couple of seconds after the navigation.
1 Reply
ratty-blush
ratty-blush10mo ago
I think if you await stuff inside onSuccess it prolongs the pending state

Did you find this page helpful?