I started using react query mutations but I found out when looking at the network request that when I call a mutation it first fetches before executing it.
Here is my mutation
const mutation= useMutation(
async (values: VoteProps) => {
await fetch("/api/test/test", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
},
onSettled: (data: any, error: any, variables: any, context: any) => {
refetch();
},
}
This is my useQuery
const { isLoading, isError, data, error, refetch } = useQuery<test>(
"test",
test,
{ refetchInterval: 30000, refetchIntervalInBackground: true }
);
The mutation changes the test useQuery values
Is there a reason for it or a way to disable that?
thank you
Returning the fetch in your mutation function will solve the problem.
Explanation
The mutation function should return a promise-like value. useMutation
waits until this promise gets either resolved or rejected and then calls the onSettled
callback.
your mutation function is a void function, so This is what happens when you call the mutation.mutate()
:
useMutation
calls the mutation functionfetch()
is called asynchronouslyundefined
valueuseMutation
calls the onSettled
callback because the mutation function has returned something. (although the fetch
has not yet been resolved)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With