I have a custom useMutation
hook:
const {
status: updateScheduleStatus,
reset: updateScheduleReset,
mutateAsync: updateSchedule,
} = useUpdateSchedule(queryClient, jobId as string);
Which I understand sets up the mutation but how would I use this if I wanted to do multiple parallel mutations?
I have tried to implement the following but the mutations execute prior to getting to the Promise.all(mutations
line.
let mutations: Array<any> = [];
schedulesForDeletion.forEach(async (schedule) => {
const resp = await monitoringService?.getSchedule(
schedule.schedule_id,
);
mutations.push(
updateSchedule({
monitoringService: monitoringService as MonitoringServiceClient,
schedule,
etag: resp?.type === "data" ? resp.headers.etag : "",
}),
);
});
console.dir(mutations);
await Promise.all(mutations);
I would have through that as mutateAsync
returns a Promise
that they would not fire in sequence but seems that they do.
Is there a way to handle this in react-query
or am I better off just performing this with axios? It would be useful to do in react-query
as I need to invalidate some queries when the mutations are successful.
running multiple mutations in parallel does work with mutateAsync
:
const { mutateAsync } = useMutation(num => Promise.resolve(num + 1))
const promise1 = mutateAsync(1)
const promise2 = mutateAsync(2)
await Promise.all([promise1, promise2])
I'm guessing in your example you push a Promise to the array, then you continue your loop and await monitoringService?.getSchedule
. Only after that returns, you fire off the second mutation.
So in that sense, it seems that this is what's "blocking" your execution. If you push the original Promise coming from getSchedule
, it should work:
schedulesForDeletion.forEach((schedule) => {
mutations.push(
monitoringService?.getSchedule(
schedule.schedule_id,
).then(resp => updateSchedule({...})
)
)
})