HuolalaTech / react-query-kit

🕊️ A toolkit for ReactQuery that make ReactQuery hooks reusable and typesafe
MIT License
355 stars 11 forks source link

InvalidateQueries on success without useDefaultOptions #34

Closed Alex-apostolo closed 1 year ago

Alex-apostolo commented 1 year ago

Hi! Let me start by saying thank you for making this amazing library. I am trying to upgrade from v1.4.8 to v2.0.1 and im having a hard time wrapping my mind around how to use middlewares to invalidate queries. I have a lot of examples such as the following:

export const useCreateProject = createMutation<void, { name: string }>({
  mutationFn: variables => axios.post(getProjectEndpoint(), toPartial(toProjectDTO)(variables)),
  useDefaultOptions: () => {
    const queryClient = useQueryClient();
    const projectsQuery = useProjects;
    return {
      onSuccess: () => {
        queryClient.invalidateQueries(projectsQuery.getKey());
      },
    };
  },
});

Since the useDefaultOptions was deprecated how can i achieve the same functionality now? It could also be useful if I could pass the queryClient to all onSuccess (im not sure if this will be part of the context i.e. ctx passed as the 3rd parameter)

liaoliao666 commented 1 year ago

You can convert it as belown. But I am not sure what u mean about this will be part of the context

const myMiddleware = useMutationNext => options => {
  const queryClient = useQueryClient()

  return useMutationNext({
    ...options,
    onSuccess: () => {
      queryClient.invalidateQueries(useProjects.getKey())
      options.onSuccess?.()
    },
    // or  override if pass a new onSuccess
    // onSuccess:
    //   options.onSuccess ??
    //   (() => {
    //     queryClient.invalidateQueries(useProjects.getKey())
    //   }),
  })
}

export const useCreateProject = createMutation<void, { name: string }>({
  mutationFn: variables =>
    axios.post(getProjectEndpoint(), toPartial(toProjectDTO)(variables)),
  use: [myMiddleware],
})
Alex-apostolo commented 1 year ago

Thanks that works! Ignore me I was confusing the use of context. Just one last thing, I was getting this type error:

Screenshot 2023-10-04 at 17 50 51

and to fix it I changed the following:

 return useMutationNext({
        ...options,
        onSuccess: (...onSuccessOptions) => {
          queryClient.invalidateQueries(useProjects.getKey());
          options.onSuccess?.(...onSuccessOptions);
        },
        // or  override if pass a new onSuccess
        // onSuccess:
        //   options.onSuccess ??
        //   (() => {
        //     queryClient.invalidateQueries(useProjects.getKey())
        //   }),
      });
    },