T
TanStack3y ago
optimistic-gold

mutationFn is optional

Why is mutationFn optional in useMutation hook? Docs say it's required. I wonder if it is intentional or if it is just a bug in types.
No description
No description
7 Replies
passive-yellow
passive-yellow3y ago
It looks like the options object for this overload signature are of type UseMutationOptions (https://github.com/TanStack/query/blob/main/packages/react-query/src/useMutation.ts#L26). This interface is defined here (https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L86) and extends from MutationObserverOptions (https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L585) which in turn extends from MutationOptions (https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L549). The MutationOptions interface defines the mutationFn as possibly undefined (https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L555). Essentially, I think this is likely an issue with the types as it doesn't align with the documentation and I don't see how a mutation can validly be defined without a mutationFn. I'm not a maintainer so this isn't an authoritative answer but I'd probably raise an issue and ask the question.
conscious-sapphire
conscious-sapphire3y ago
you can define a global mutation function, just like you can define a global query function
conscious-sapphire
conscious-sapphire3y ago
Default Query Function | TanStack Query Docs
If you find yourself wishing for whatever reason that you could just share the same query function for your entire app and just use query keys to identify what it should fetch, you can do that by providing a default query function to TanStack Query:
conscious-sapphire
conscious-sapphire3y ago
that's why it's optional at the end of the day, there must be a function, but you don't necessarily need to pass it to useMutation
passive-yellow
passive-yellow3y ago
Interesting! That makes sense; sorry and thanks for clearing that up 🙌 would it be worth updating the documentation? I'd be happy to do this
conscious-sapphire
conscious-sapphire3y ago
definitely. Thanks 🙏
passive-yellow
passive-yellow3y ago
No worries, I've raised https://github.com/TanStack/query/pull/4837 🙂

Did you find this page helpful?