T
TanStackβ€’3y ago
quickest-silver

Callback after final mutations when dealing with consecutive mutations

Per the docs, mutation.mutate lets you pass in an onSuccess which only runs after the last mutation in a series of mutations is complete (think removing rows from a server-data driven table). However, as also mentioned in the docs, there are situations where that onSuccess won't be called (i.e. the overlay that calls the mutation unmounts). Is there a way to get the same behavior with the onSuccess passed into useMutation? The goal is to only invalidate relevant queries once the series of mutations is complete. If I invalidate after every mutation alongside optimistic updates, it ends up with some fun back and forth in the UI. I can whip up a codesandbox if needed.
4 Replies
probable-pink
probable-pinkβ€’3y ago
I wanted to add a callback for that, but then found out that you can just check for if queryClient.isMutating({ mutationKey }) > 1 before firing up the invalidation
quickest-silver
quickest-silverOPβ€’3y ago
Oh, thought I had tried that. πŸ€” I'll give it another shot.
probable-pink
probable-pinkβ€’3y ago
Dominik πŸ‡ΊπŸ‡¦ (@TkDodo)
@andrew8088 Ah that's an interesting one. Concurrent mutations are tricky. The best way I know is to tag your mutations with a mutationKey, then guard your call to invalidateQueries with: if (queryClient.isMutating({ mutationKey )}> 1)
Twitter
quickest-silver
quickest-silverOPβ€’3y ago
That works great. I think I had checked the affected query key, rather than the mutation key. πŸ€¦β€β™‚οΈ Thank you!

Did you find this page helpful?