How To Optimally Combine Multiple Axios Responses
I am working with a React app. I have to create 2 objects using responses from 3 different APIs. For example: DataObject1 will be created using API1 and API2 DataObject2 will be
Solution 1:
Looks fine.
You can change this
axios.all([requestOne, requestTwo, requestThree]).then(axios.spread((...responses) => {
const dataObject1 = createDataObject1(responses[0], responses[1]);
const dataObject 2 = createDataObject2(responses[0], responses[1], responses[2]);
// use/access the results
})).catch(errors => {
// react on errors.
})
to
axios.all([requestOne, requestTwo, requestThree]).then(axios(response) => {
const dataObject1 = createDataObject1(responses[0], responses[1]);
const dataObject 2 = createDataObject2(responses[0], responses[1], responses[2]);
// use/access the results
}).catch(errors => {
// react on errors.
})
because spreading and resting is redundant.
If you don't want to use them like responses[0]
, responses[1]
, etc then you can use:
axios.all([requestOne, requestTwo, requestThree]).then(axios.spread((response1, response2, response3) => {
const dataObject1 = createDataObject1(response1, response2);
const dataObject 2 = createDataObject2(response1, response2,response3);
// use/access the results
})).catch(errors => {
// react on errors.
})
Solution 2:
Are you using thunk middleware to make async calls in Redux? I don't want to assume that you are, but that seems like a good basic approach here.
const requestOne = axios.get(API1);
const requestTwo = axios.get(API2);
const requestThree = axios.get(API3);
Okay. So now requestOne.data
has the result of making the axios get request. Or, would if the thunk creator was async and the code was const requestOne = await axios.get(API1);
Do you need to parse the data further from request___.data ?
If not you can just have
const dataObj1 = { response1: requestOne.data, response2: requestTwo.data }
const dataObj2 = { ... dataObject1, response3: requestThree.data };
Full answer:
// store/yourFile.js codeexportconstYourThunkCreator = () => async dispatch => {
try {
constconst requestOne = await axios.get(API1);
// other axios requestsconst dataObj1 = { response1: requestOne.data, response2: requestTwo.data }
const dataObj2 = { ... dataObject1, response3: requestThree.data };
// other codedispatch(// to Redux Store);
} catch (error) {
console.error(error);
}
Post a Comment for "How To Optimally Combine Multiple Axios Responses"