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

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

Closed
Floriferous opened this issue Jan 7, 2025 · 1 comment
Labels
duplicate This issue or pull request already exists

Comments

@Floriferous
Copy link

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

@TkDodo
Copy link
Collaborator

TkDodo commented Jan 8, 2025

@TkDodo TkDodo closed this as completed Jan 8, 2025
@TkDodo TkDodo added the duplicate This issue or pull request already exists label Jan 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate This issue or pull request already exists
Projects
None yet
Development

No branches or pull requests

2 participants