Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useIsMutating gets stuck on page navigation when using mutation hook with NextJS Server Action if there's ongoing post requests #7454

Open
flnx opened this issue May 18, 2024 · 0 comments

Comments

@flnx
Copy link

flnx commented May 18, 2024

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

With.Server.Action_preview.mp4

Using mutation with NextJS Route Handler

With.Route.Handler_preview.mp4

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant