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) {
}
});
useEffect(() => {
if (!hasRun.current) {
hasRun.current = true;
mutate();
}
}, []);
return <div>{status}</div>;
}
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>;
}
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
duplicate of: