T
TanStack3y ago
extended-salmon

Chain useMutation together, make them rely on one another

Hi all, real quick react-query question (maybe not so quick!) I'm a bit stumped. Inside of our application we do a bit of promise chaining. This serves two purposes 1: Logically, the promise must complete before another one gets sent, this is just how the application works 2: The execution of the promise relies on data from the response of the previous promise. For example, we send an order (the DB generates an order number and sends it in the response) and then we use said order number to put on the customers receipt. I'd like to replace the promise chaining with react-query mutations for a few reasons, its a cleaner experience, it will give us a bit more control over each step in the process (showing the user what step in the process their order submission is at or what have you using loading states) and also allow us to retry queries that fail until they succeed, which is not something easily done with promise chaining unless we wanted 5 million lines of duplicated code. i thought about putting the whole process inside of a usemutation, but this kinda defeats the point of the granularity of them all being seperate as we still wouldn't really get control over each step in the process what is the best way to go about this? struggling to wrap my head around it. thanks!
5 Replies
conscious-sapphire
conscious-sapphire3y ago
It sounds like you could do this via mutate > onSuccess > mutateTwo
ratty-blush
ratty-blush3y ago
i personally prefer using mutateAsync in this case..
async function handleProcessing() {
const resp1 = await mutationOne.mutateAsync()
const resp2 = await mutationTwo.mutateAsync()
}
async function handleProcessing() {
const resp1 = await mutationOne.mutateAsync()
const resp2 = await mutationTwo.mutateAsync()
}
conscious-sapphire
conscious-sapphire3y ago
This is also valid, although I tend to prefer callbacks, personally :reactquery:
extended-salmon
extended-salmonOP3y ago
Using the callbacks are great, but it limits access to the scope of the data To pass the data in where it actually has scope, we would need to call example.mutate inside of the function with scope. If we use callbacks, we won't have scope of the data
conscious-sapphire
conscious-sapphire3y ago
The callbacks receive the mutation variables as an argument

Did you find this page helpful?