Skip to content
Source
Sign inSign up
TanStack/query

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

Send to my agent
Closedflnx(GitHub profile, opens in a new tab) opened this issue 2 comments

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

  1. I get a similar thing but when loading a useQuery. If I navigate to fast with next link when a query isLoading, then the it gets stuck in its loading state. On latest version of react query "@tanstack/react-query": "^5.66.0",

  2. This seems to be a nextJs problem, something around how they have implemented server actions. If we change the mutationFn to log how the requests start / end:

    mutationFn: async (id: number) => {
      console.log('begin mutation',id)
      const result = await deleteSomething(id)
      console.log('end mutation', id)
      return result
    },

    we can see that await deleteSomething, which does a server action, never finishes after we’ve moved to a separate page. That’s why useIsMutating feels “stuck”, because it actually is stuck. If await deleteSomething never returns, we have a never fulfilling promise.

    This is what I get roughly when I click 5 times:

    begin mutation 1
    begin mutation 2
    begin mutation 3
    begin mutation 4
    end mutation 1
    begin mutation 5
    end mutation 2
    end mutation 3

    for mutations 4 and 5, the end mutation log is never received. The promise definitely never resolves. From looking at the network tab log, I can’t even see all the requests being started. I think that’s because nextJs server functions run in serial - one by one. So it’s totally possible that they never start, and somehow, that means they don’t resolve the promise they initially created?

    So I think this needs to be addressed with the NextJs team, there isn’t really anything we can do on our end. If we get a promise returned that is always in pending state, what useIsMutating shows is correct.

  3. TkDodo closed this

  4. TkDodo added labelsupstream

Sign in to join this conversation.