invalidateQueries Error in simple react app using react-query

Viewed 40

i'm beginner of react-query.
i made a simple CRUD app. (MemoList)
when update content, react-query invalidateQueies not working...
this is my code.

export function updateOne(updateContent, id) {
  return api.patch(`/api/content/${id}`, updateContent);
}
export function findOne(id) {
  return api.get(`/${id}`);
}

UpdateList.js

 const mutations = useMutation(updateOne, {
    onMutate: (value) => {
      console.log("value", value);
    },
  });

when submitButton triggers,

  mutations.mutate(updateContentObj, id);
  navigate(`/detail/${id}`);

detail.js

  const { isLoading, isError, data, error } = useQuery(
    ["detail"],
    () => {
      return findOne(id);
    },
    {
      select: (data) => {
        return data.data;
      },
      onSuccess: () => {
        queryClient.invalidateQueries(["detail"]);
      },
      onError: () => {
        console.error(`Error: ${error.message}`);
      },
    }
  );

result of onMutate console -> console show updateValue correctly.
however, in detail page, it was not updated. just same before update. how can i fix it?

1 Answers

Either use the onSuccess callback function on the useMutation hook or on the mutate method to invalidate a cache entry. Keep in mind that your mutate function only take one argument to pass your variables.

const mutations = useMutation(updateOne, {
  onSuccess: () => {
    queryClient.invalidateQueries(["detail"]);
  }
});

mutations.mutate(({ updateContent: updateContentObj, id }), {
  onSuccess: () => {
    queryClient.invalidateQueries(["detail"]);
  }
});

export function updateOne({ updateContent, id }) {
  return api.patch(`/api/content/${id}`, updateContent);
}
Related