T
TanStack3y ago
adverse-sapphire

Side effects inside onMutate

Is it ok to have side effects in the onMutate function? For example when a query value goes from false to true:
useMutation(callApi, {
onMutate: async (newValue) => {
await queryClient.cancelQueries([key]);

const previousValue = queryClient.getQueryData([key]);

if (!oldValue && newValue) {
console.log('trigger side-effect');
}
queryClient.setQueryData([key], () => newValue);

return { oldValue };
},
onError: (err, _, context) => {
queryClient.setQueryData([key], context?.oldValue);
captureException(err);
},
});
useMutation(callApi, {
onMutate: async (newValue) => {
await queryClient.cancelQueries([key]);

const previousValue = queryClient.getQueryData([key]);

if (!oldValue && newValue) {
console.log('trigger side-effect');
}
queryClient.setQueryData([key], () => newValue);

return { oldValue };
},
onError: (err, _, context) => {
queryClient.setQueryData([key], context?.oldValue);
captureException(err);
},
});
5 Replies
exotic-emerald
exotic-emerald3y ago
I would probably try to catch the side effect before calling the mutate function. What is the side effect you need to run?
adverse-sapphire
adverse-sapphireOP3y ago
I need to show a notification when derived query data "was false and is now true". It seems like the right place to access before/after values
exotic-emerald
exotic-emerald3y ago
Yeah showing notifications from onMutate onSuccess etc... sounds ok to me. Do you still run the mutation when newValue==oldValue though? If you do that check before triggering the mutation, that could probably save an API call.
adverse-sapphire
adverse-sapphireOP3y ago
Oh, that's smart, we don't check for equality in any of our queries, I'll start doing that.
xenial-black
xenial-black3y ago
Yeah, side effects in callbacks are fine

Did you find this page helpful?