T
TanStack•16mo ago
correct-apricot

How to Combine and Handle Multiple Mutations with Shared Success and Error Handling in React Query?

I have two mutations (2 fetch put request) in the same react component, i have modals i show for both on success and onerror, how can i combine those two mutations since i dont want to show one modal for each mutation.
8 Replies
stormy-gold
stormy-gold•16mo ago
if they fire at the same time, you can have mutation that fires two requests
correct-apricot
correct-apricotOP•16mo ago
I have the both mutation in a submit function in the component right now, you mean i should combine them in to one mutation?
stormy-gold
stormy-gold•16mo ago
yep
correct-apricot
correct-apricotOP•16mo ago
Do you have a link to a code example or any documentation about that?
stormy-gold
stormy-gold•16mo ago
I mean ... a mutationFn is just a function that returns a Promise. A Promise can be one request or multiple requests (with Promise.all)
mutationFn: () => {
return Promise.all([makePostRequest1(), makePostRequest2()]
}
mutationFn: () => {
return Promise.all([makePostRequest1(), makePostRequest2()]
}
correct-apricot
correct-apricotOP•16mo ago
So basically i just create a function like you show and call the mutations from there? What if i need to get parameters sent to each request?
stormy-gold
stormy-gold•16mo ago
send them in as variables. I don't know your use-case and "what if" games are pretty tiring. You can show a minimal reproduction in codesandbox or stackblitz and I'll take a look
correct-apricot
correct-apricotOP•16mo ago
@TkDodo 🔮 This seems to be working.
const confirm = () => {
mutate({ param1, param2, param3 });
};

export const useUpdateItem = () => {
return useMutation({
mutationFn: ({ param1, param2, param3}) => {
return Promise.all([
request1(param1),
request2(param2, param3)
]);
}
});
};
const confirm = () => {
mutate({ param1, param2, param3 });
};

export const useUpdateItem = () => {
return useMutation({
mutationFn: ({ param1, param2, param3}) => {
return Promise.all([
request1(param1),
request2(param2, param3)
]);
}
});
};
Does it looks correct to you?

Did you find this page helpful?