TanStackT
TanStackโ€ข3y agoโ€ข
6 replies
full-green

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 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:

mutations.push(
  new Promise((resolve, reject) => {
    createPerson(
      {
        companyId: id,
        person: parsedPersonValues,
      },
      {
        onError: reject,
        onSuccess: () =>
          resolve(
            translate('feedback.success.createPerson', {
              replacements: [response.name],
            }),
          ),
      },
    );
  }),
);

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 ๐Ÿ™‚
Was this page helpful?