query: useMutation adds undefined to TResult of MutateFunction type
Describe the bug
useMutation changes the return type of provided promise by adding undefined to it.
To Reproduce
const apiCall = () => new Promise<string>(resolve => resolve());
const useExample = async () => {
const [mutateCall] = useMutation(apiCall);
const response = await apiCall(); // string
const mutateR = await mutateCall(); // string | undefined
};
Wrapping a function in useMutation adds a undefined to it’s returned promise
Expected behavior
The provided function’s return type should not be changed.
Desktop (please complete the following information):
- Version: 23
Additional context
I don’t see any reason why this would be required. Together with #1077 this is making migration to this library pretty unnecessarily painful by imposing this opinionated types.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 2
- Comments: 22
I think the PR above fixes this issue. v3 will be awesome!
What about providing two mutate functions? One for callbacks and for promises?
Callback version:
Promise version:
Then
mutatewould return nothing,mutateAsyncwould return a promise andthrowOnErrorcan be removed.@TkDodo the full example is a little more complex. I am using Formik, which allows to track an
isSubmittingstate:Inside
MyForm,myApiCallismutate:and in the parent component I can just have:
This allows me to rely on
react-queryAND keep the loading logic in the child form component. I could do it by exposing formik helpers:But I don’t like this, since I feel it breaks encapsulation. My parent component should not really know about formik helpers.
Honestly, I really do not see the advantage of the callbacks.
Unfortunately not everything can be done in the
onSuccesscallback, for interop with other code I need from time to time to access the Promise result. I believe that the| undefinedunion should be added only whenthrowOnErrorisfalse; ifthrowOnErroris true, the result can never beundefinedif the promise resolves.Hi @Haaxor1689! Issue #1077 will be fixed in V3 and this type is actually correct because the mutate function by default returns
undefinedwhen the mutation fails