openapi-typescript icon indicating copy to clipboard operation
openapi-typescript copied to clipboard

Params are missing in mutationKey

Open adityaa72 opened this issue 10 months ago • 3 comments

openapi-react-query version

0.2.9

Description

MutationKey don't include params as can be seen in this code

useMutation(
        {
          mutationKey: [method, path],
          mutationFn: async (init) => {
            const mth = method.toUpperCase() as Uppercase<typeof method>;
            const fn = client[mth] as ClientMethod<Paths, typeof method, Media>;
            const { data, error } = await fn(path, init as InitWithUnknowns<typeof init>);
            if (error) {
              throw error;
            }

            return data as Exclude<typeof data, undefined>;
          },
          ...options,
        },
        queryClient,
      )

Use case

I wanna check if a mutation with a specific id is mutating or not. Here id should be used for creating mutation key

Also there is a request to add createQueryKey function in your package

import { createQueryKey } from "@/client/utils";
import { useIsMutating } from "@tanstack/react-query";

export const usePayoutWalletState = (id: string) => {
  const isMutating = useIsMutating({
    mutationKey: createQueryKey("put", "/payout-wallets/{id}/set-default"),
  });
  return {
    isMutating,
  };
};

Reproduction

This issue is not related to any browser or specific conditions.

Expected result

I expected that mutationKey should include params same as used in queryOptions

const queryOptions: QueryOptionsFunction<Paths, Media> = (method, path, ...[init, options]) => ({
    queryKey: [method, path, init as InitWithUnknowns<typeof init>] as const,
    queryFn,
    ...options,
  });

Extra

adityaa72 avatar Jan 13 '25 14:01 adityaa72

You are right, we should be providing parameters to the mutationKey, the same way we do with queryKey. Happy to review a PR for that!

kerwanp avatar Jan 23 '25 13:01 kerwanp

It seems that init has to be passed late unlike useQuery, so I don't think that this is possible.

Furthermore, it looks like that the role of queryKey and mutationKey is very different, so I don't think it's the right tool for checking specific mutations.

musjj avatar Jan 23 '25 13:01 musjj

A feature that is not implemented in openapi-react-query is the ability to provide parameters in useMutation that become optional when using mutate. In this case, it would be possible to use those initial parameters as a mutation key.

const { mutate } = $query.useMutation('GET', '/api/{authorId}/posts', { params: { path: { authorId: 2 } } }) 

// authorId is now optional
mutate({
  params: { query: { page: 4 } }
})

As I have never used mutation keys before, I am not really aware of the different use cases.

kerwanp avatar Jan 23 '25 18:01 kerwanp

@kerwanp Any update? It's been a while.

adityaa72 avatar May 16 '25 05:05 adityaa72