Skip to content
Source
Sign inSign up
TanStack/query

Running a mutation in a useEffect hook on mount causes mutation to remain stuck in pending #8512

Send to my agent
ClosedFloriferous(GitHub profile, opens in a new tab) opened this issue 1 comment

Describe the bug

I'd like to call a mutation when my component mounts, only once. Doing this with a ref and useEffect (to avoid concurrent double useEffect calls) appears to cause the mutation to never succeed, even though all of the code is called properly. It therefore remains in status: "pending" forever.

If I wrap the mutation call in a timeout with 0ms of delay, it works.

Your minimal, reproducible example

Can take some time to do this another day

Steps to reproduce

This fails:

function MyComponent() {
  const hasRun = useRef(false);
  const { mutate, status } = useMutation({
    ...
    onSuccess(response) {
      // This works, the hook is called with the right response
    }
  });

  useEffect(() => {
    if (!hasRun.current) {
      hasRun.current = true;
      mutate();
    }
  }, []);

  return <div>{status}</div>; // Stays in pending forever
}

This works:

function MyComponent() {
  const hasRun = useRef(false);
  const { mutate, status } = useMutation({ ... });

  useEffect(() => {
    if (!hasRun.current) {
      hasRun.current = true;
      setTimeout(() => {
        mutate();
      }, 0);
    }
  }, []);

  return <div>{status}</div>; // Stays in pending forever
}

Expected behavior

I expect the mutation to succeed properly.

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

  • React
  • NextJS (with "use client")

Tanstack Query adapter

react-query

TanStack Query version

5.62.15

TypeScript version

5.7.2

Additional context

No response

  1. TkDodo closed this

  2. TkDodo added labelsduplicate

Sign in to join this conversation.