TanStackT
TanStack4mo ago
7 replies
yucky-gold

context.client undefined in react query V5

The docs indicate that the onMutate option in the useMutation hook should be a context item that contains the query client. That would then allow us to use something like context.client.setQueryDate without calling queryClient = useQueryClient().

onMutate: async (updatedFailureMode) => {
      await queryClient.cancelQueries({
        queryKey: ["dfmea-data", projectId],
      });
      const previousData = queryClient.getQueryData(["dfmea-data", projectId]);
      queryClient.setQueryData(["dfmea-data", projectId], (oldData) => {
        return oldData.map((item) =>
          item.failureModeId === updatedFailureMode.failureModeId
            ? updatedFailureMode
            : item
        );
      });
      return { previousData };
    },


For example, I would love to instead of the above do something like:

onMutate: async (updatedFailureMode, context) => {
      await context.client.cancelQueries({
        queryKey: ["dfmea-data", projectId],
      });
      const previousData = context.client.getQueryData(["dfmea-data", projectId]);
      context.client.setQueryData(["dfmea-data", projectId], (oldData) => {
        return oldData.map((item) =>
          item.failureModeId === updatedFailureMode.failureModeId
            ? updatedFailureMode
            : item
        );
      });
      return { previousData };
    },


The docs say this should work but I get an error saying context.client does not exist.

https://tanstack.com/query/latest/docs/framework/react/guides/mutations
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a useMutation hook. Here's an example of a mutation t...
Mutations | TanStack Query React Docs
Was this page helpful?