Axios: send multiple Axios requests
>As our application grows bigger, I ran into situations where multiple Axios requests need to be send in one actions function.
As the start, here is what we can do:
First, let's import Axios and define the different URLs we wanted to access.
import axios from 'axios'
const dataObj1 = {key: fetch1, url : 'https://myfirsturl'}
const dataObj2 = {key: fetch1, url : 'https://myfirsturl'}
const dataObj3 = {key: fetch1, url : 'https://myfirsturl'}
Create array of data calls
const dataObjArray = [dataObj1, dataObj2, dataObj3]
const axiosConfig = {offset:0, max:10000}
const axiosDataCallArray = dataObjArray.map((d)=>{
return axios.post(d.url, { d.key, ...axiosConfig } )
})
Each axios.post() will return a Promise. In axios, we have a funciton called .all() to handle an array of Promises. Using axios.all() to do all data calls
axios.all(axiosDataCallArray).then(
axios.spread((...reponses)=>{
const response1 = responses[0]
const responseData1 = responses[0].data
const response2 = responses[1]
const responseData2 = responses[1].data
const response3 = responses[2]
const responseData3 = responses[2].data
})
.catch( (err) =>{
console.error(err)
})
)