T
TanStack•2y ago
harsh-harlequin

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
correct-apricot
correct-apricot•2y ago
if they fire at the same time, you can have mutation that fires two requests
harsh-harlequin
harsh-harlequinOP•2y 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?
correct-apricot
correct-apricot•2y ago
yep
harsh-harlequin
harsh-harlequinOP•2y ago
Do you have a link to a code example or any documentation about that?
correct-apricot
correct-apricot•2y 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()]
}
harsh-harlequin
harsh-harlequinOP•2y 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?
correct-apricot
correct-apricot•2y 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
harsh-harlequin
harsh-harlequinOP•2y 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?