[Types] onError's context is unknown when inferring TVariables in useMutation if using a mutation function with parameters (but works without parameters) #3434
-
There's a functionality for inferring the return value type of the I think inferring works for mutation functions without parameters, but does not work for mutation functions with parameters. For optimistic updates, that return value can be used via // mock mutation function without parameter
async function fetchWithoutParam() {
return { userId: "1" };
}
const updateUserMutation1 = useMutation(fetchWithoutParam, {
onMutate: async () => {
await queryClient.cancelQueries(queryKey);
const userBeforeMutation = queryClient.getQueryData<QueryData>(queryKey);
...
// returned value here is part of the `onError`'s `context` variable
return { userBeforeMutation };
},
onError: (err, _, context) => {
// getting `userBeforeMutation` from `onMutate`'s return
// ✅ here, `context` is typed correctly
const userBeforeMutation = context?.userBeforeMutation;
if (userBeforeMutation) {
queryClient.setQueryData<QueryData>(queryKey, userBeforeMutation);
}
console.error("Error while updating user:", err);
},
... This works great and everything is inferred. But there is a variant where something does not work: When the mutation function uses parameters. When using such a mutation function, // mock mutation function with parameter
async function fetchWithParam({ userToUpdate }: { userToUpdate: User }) {
return { userId: "1" };
}
// `fetchWithParam` instead of `fetchWithoutParam`
const updateUserMutation2 = useMutation(fetchWithParam, {
onMutate: async ({ userToUpdate }) => {
...
},
onError: (err, _, context) => {
// ❌ here, `context` is unknown
const userBeforeMutation = context?.userBeforeMutation;
...
},
... For this example, One can easily circumvent this problem by setting the type definition of the mutation function parameter for the onMutate: async ({ userToUpdate }: { userToUpdate: User }) => { With this type defintion in place, Is this expected? For reference, here is a CodeSandbox with the three variants:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It's a somewhat known TS limitation, yes: https://tkdodo.eu/blog/react-query-and-type-script#optimistic-updates |
Beta Was this translation helpful? Give feedback.
It's a somewhat known TS limitation, yes: https://tkdodo.eu/blog/react-query-and-type-script#optimistic-updates