useIsMutating gets stuck on page navigation when using mutation hook with NextJS Server Action if there's ongoing post requests
Describe the bug
When using the mutation hook in combination with NextJS Server Action and the user makes multiple POST requests (e.g. likes/deletions), if the ongoing requests haven't finished by the time the user decides to navigate to another page, the useIsMutating hook will stop tracking them and it will get stuck with the number of unfinished requests from the previous page.
This problem does not occur when using a Route Handler. It only occurs in a combination with Server Actions!
Your minimal, reproducible example
https://codesandbox.io/p/github/flnx/next-actions-and-tanstack-mutations/main
Steps to reproduce
The problem will occur when using this hook (with server actions)
export const useLikeImageWithServerAction = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: likeImage, // <- This is a server action
onMutate: (imgData) => {
// update data
},
onError: (err, imageData, context) => {
// roll back
},
});
};
A work-around is to use the hook that makes requests to a route handler:
export const useLikeImageWithRouteHandler = () => {
const queryClient = useQueryClient();
// A working solution
return useMutation({
mutationFn: async (imageData: any) => {
const res = await fetch("/api/user/favorites", {
method: "POST"
});
if (!res.ok) {
throw new Error(await res.text());
}
return {
id: imageData.id
}
},
onMutate: (imgData) => {
// update data
},
onError: (err, imageData, context) => {
// roll back
},
});
};
Expected behavior
I expected the useIsMutating hook to update correctly when navigating to another page when using server actions, just like using route handlers
How often does this bug happen?
Every time
Screenshots or Videos
Using mutation with NextJS Server Action
https://github.com/TanStack/query/assets/32278279/966bd4af-1476-488f-b773-fc4d5fb80b7a
Using mutation with NextJS Route Handler
https://github.com/TanStack/query/assets/32278279/5ded3400-4458-46bb-9d31-8009729fc7b8
Platform
Windows 11, Firefox 126.0 (64-bit)
Tanstack Query adapter
react-query
TanStack Query version
5.20.5
TypeScript version
5
Additional context
No response