Skip to content
Discussion options

You must be logged in to vote

You need to explicitly specify the 4th generic of useMutation (TContext).
React Query does not infer the return type of onMutate, so without providing TContext, the type defaults to {}, which is why context.snapshot gives a TS error.

return useMutation<
Result,
Error,
Variables,
{ snapshot: User | undefined }

({
onMutate: async () => {
const snapshot = queryClient.getQueryData(["user"]);
return { snapshot };
},

onError: (err, variables, context) => {
if (context?.snapshot) {
queryClient.setQueryData(["user"], context.snapshot);
}
},
});

Why this happens

UseMutationOptions has 4 generics:
TData, TError, TVariables, TContext

If you only provide 3, TContext falls back to its default:

TCont…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by qkrrjsgudtkdjq-bot
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants