Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react query refetches before mutation are executed

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

like image 566
Maxime Ghéraille Avatar asked Oct 19 '25 03:10

Maxime Ghéraille


1 Answers

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():

  1. useMutation calls the mutation function
  2. fetch() is called asynchronously
  3. the mutation function returns immediately with undefined value
  4. useMutation calls the onSettled callback because the mutation function has returned something. (although the fetch has not yet been resolved)
  5. query gets refetched
  6. the mutation and query requests get response from the server some moments later
like image 95
Saeed Mosavat Avatar answered Oct 20 '25 18:10

Saeed Mosavat