Does `useMutation().mutate()` batch calls to `onSuccess`?
I have an array of persons I want to create in some kind of API using a POST request. Unfortunately my Backend only exposes a singular
Thanks for any help 🙂
create-person endpoint.
So I loop over this array and create a bucket of Promises using the mutations returned from useMutation() - they are all the same call in the end. I add a onSuccess callback. The code looks something like this:
createPerson() comes from a custom hook that returns useMutation() with a queryFn and some callbacks.
I later than call Promise.allSettled(mutations) to wait for all requests and work display the results (errors or success toasts).
When triggering with just one new person it works fine. But when triggering this with multiple persons, only the last Promise resolves or rejects. All other Promises never fulfil - they all remain pending causing my Promise.allSettled() to never trigger and causing my app to hang in an infinite "submitting" state although all API calls were made successfully.
I traced it down to the onSuccess on the actual mutate() call not firing (onError and onSettled also don't trigger). Does react-query do some sort of batching here?Thanks for any help 🙂
5 Replies
secure-lavender•3y ago
onSuccess is only called for the last observer if you have it on .mutatestormy-goldOP•3y ago
Hmmm okay I figured 🤔
secure-lavender•3y ago
Mutations | TanStack Query 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:
secure-lavender•3y ago
what you want is one
useMutation where the mutationFn does multiple fetch calls, then returns a Promise.allSettled from withinstormy-goldOP•3y ago
That's what I thought as well - also makes calling it from the component way clearer
Thank you! 🙂