How do I invalidate the useMutation on success

439 Views Asked by At

Hi I have below mutation :

export const useUserSearch = (data) => {
  return useMutation({
    mutationKey: ["user-search", data],
    mutationFn: fetchUser,
  });
};

I am using it in the component :

 const {
    mutate,
    data: userInfo,
    isLoading: userInfoLoading,
  } = useUserSearch();

Now I have another Mutation which gets called on updation request like below :

 const handleCreateRoleConfirm = (data) => {
    createRoleMutate(data, {
      onSuccess: () => {
        queryClient.invalidateQueries("user-search"); // trying to invalidate the above mutaiton
        showAlert({
          message: "The record has been created successfully",
          variant: "success",
        });

        setIsAddDialogOpen(false);
      },
    });
  };

Now here in the onsuccess I am trying to invalidate the useUserSearch hooks mutation . But it does not work. Seems like it is not invalidation it an rerigging the api . How do I fix this ?

2

There are 2 best solutions below

0
On

you can call the mutate function with the undefined value to invalidate the mutation cache. So, in your onSuccess callback, you can try calling mutate(undefined) to invalidate the useUserSearch hook mutation.

const handleCreateRoleConfirm = (data) => {
  createRoleMutate(data, {
    onSuccess: () => {
      mutate(undefined); // call the mutate function with undefined value to invalidate the mutation cache
      showAlert({
        message: "The record has been created successfully",
        variant: "success",
      });
      setIsAddDialogOpen(false);
    },
  });
};

another way of doing this is to use queryClient.invalidateQueries() method with the exact flag set to false to invalidate all mutations with the same key. So, in your onSuccess callback, you can try calling queryClient.invalidateQueries("user-search", {exact: false}) to invalidate the useUserSearch hook mutation.

const handleCreateRoleConfirm = (data) => {
  createRoleMutate(data, {
    onSuccess: () => {
      queryClient.invalidateQueries("user-search", {exact: false}); // invalidate all mutations with the same key
      showAlert({
        message: "The record has been created successfully",
        variant: "success",
      });
      setIsAddDialogOpen(false);
    },
  });
};
0
On
  1. you can only invalidate queries, not mutations. Mutations are there to fire off data to the backend and update state there. You can't "invalidate" that because its not a resource / query.
  2. the queryKey you pass to queryClient.invalidateQueries needs to be an array. So given that you have a query with the queryKey: ["user-search", data], you can target it with queryClient.invalidateQueries(['user-search]') instead of queryClient.invalidateQueries('user-search')