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β’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 invalidationquickest-silverOPβ’3y ago
Oh, thought I had tried that. π€ I'll give it another shot.
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-silverOPβ’3y ago
That works great. I think I had checked the affected query key, rather than the mutation key. π€¦ββοΈ Thank you!