Multiple API requests #4505
-
So we have a RTK Query API set up, it works great. We have one instance where when the user clicks a button it needs to:
The way I implemented this initially is all done within a single react component function GoButton(props) {
const [createThingA, createThingAResults] = ourApi.endpoints.thingACreate.useMutation();
const [createThingB, createThingBResults] = ourApi.endpoints.thingBCreate.useMutation();
const [createThingC, createThingCResults] = ourApi.endpoints.thingCCreate.useMutation();
function onClick() {
createThingA(props.thingADetails);
createThingB(props.thingBDetails);
}
if (createThingAResults.isSuccess && createThingBResults.isSuccess) {
createThingC(createThingAResults.data.id, createThingBResults.data.id);
}
if (createThingCResults.isSuccess) {
navigate(`/url/${thingCResults.data.id/`);
}
return <button onClick={onClick}>Go!</button>;
} kind of thing (with error checking, loading spinner, etc. Is this a sensible way to work? In some ways it feels kind of elegant, in other ways kind of horrific. Would it be better to write a custom queryFn that wraps all of that inside a single mutation query? If so, is there an easy way I can use the query / mutation details set up in the Am I missing something obvious? What kinds of sneaky bugs are lurking in this type of thing that I've not thought about? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Seems like that would work better with standard async logic: async function onClick() {
const [resultA, resultB] = await Promise.all([
createThingA(props.thingADetails).unwrap(),
createThingB(props.thingBDetails).unwrap()
])
// both must have succeeded
const resultC = await createThingC(resultA.data.id, resultB.data.id).unwrap();
navigate(`/url/${resultC.data.id/`);
} |
Beta Was this translation helpful? Give feedback.
Seems like that would work better with standard async logic: