React Query optimistic update reverts cache before updating

Viewed 306

I have a custom hook which I want to use to perform an optimistic update. I am encountering a weird issue where the optimistic update occurs, then the cache is immediately reverted back to the previous cache (not sure why), and then the onSuccess queries invalidate and set the cache to what my original optimistic update did.

What this looks like is my item is updated, reverted, and updated again (blinking). For some reason, this only works with a few of the mutations I do. I think specifically larger mutations.

Can you tell any reason why this revert is happening? Thanks!

export const useFormMutation = (formId: string) => {
  const queryClient = useQueryClient();

  return useMutation(
    (newForm: IForm) => {
      return fetch(
        "MY URL",
        {
          method: "POST",
          body: JSON.stringify(newForm),
        }
      ).then((response) => response.json());
    },
    {
      onMutate: async (newForm) => {
        await queryClient.cancelQueries(["form", formId]);
        const previousForm = queryClient.getQueryData(["form", formId]);
        queryClient.setQueryData(["form", formId], () => newForm);
        return previousForm;
      },
      onSuccess: () => {
        queryClient.invalidateQueries(["form", formId]);
      },
    }
  );
};
0 Answers
Related