T
TanStack13mo ago
frail-apricot

mutateAsyc and onSuccess

Hi. I was under the impression that onSuccess callback is not called for mutateAsync. My use case is that I only want to invalidate after a handful of simultaneous mutateAsyncs are settled. Am I wrong in my assumption? Because onSuccess callback seems to be triggering on mitateasync
5 Replies
wise-white
wise-white13mo ago
Mutations | TanStack Query React Docs
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a useMutation hook. Here's an example of a mutation that adds a new todo to the server:
frail-apricot
frail-apricotOP13mo ago
Thanks for the reply. I was hoping more for for concurrent mutations and only invalidating once they're all settled.
wise-white
wise-white13mo ago
That's what onSuccess given to mutate does. Are these different mutations? What about
await Promise.all([
mutateAsyncOne(...),
mutateAsyncTwo(...),
mutateAsyncThree(...)
])

// Your invalidate here
await Promise.all([
mutateAsyncOne(...),
mutateAsyncTwo(...),
mutateAsyncThree(...)
])

// Your invalidate here
other-emerald
other-emerald13mo ago
The easiest way to get there is to give them a mutationKey and then check for if (queryClient.isMutating({ mutatiounKey }) === 1) inside the onSuccess callback like:
useMutation({
mutationKey: ['update-project'],
mutationFn: updateProject,
onSuccess: () => {
if (queryClient.isMutating({ mutationKey: ['update-project'] }) === 1) {
queryClient.invalidateQueries(['projects'])
}
}
})
useMutation({
mutationKey: ['update-project'],
mutationFn: updateProject,
onSuccess: () => {
if (queryClient.isMutating({ mutationKey: ['update-project'] }) === 1) {
queryClient.invalidateQueries(['projects'])
}
}
})
frail-apricot
frail-apricotOP13mo ago
Lovely! Thank you so much. Elegant solution too.

Did you find this page helpful?