Please check my code first.
const arr = ['liver', 'heart', 'brain']
const url1 = `www.hospital.com/diseaseName?liver`
const url2 = `www.hospital.com/diseaseName?heart`
const url3 = `www.hospital.com/diseaseName?brain`
const request1 = axios.get(url1)
const request2 = axios.get(url2)
const request3 = axios.get(url3)
const fetchData = () => {
axios.all( [request1, request2, request3] )
.then(axios.spread((...response) => {
const responseOne = response[0].data
const responseTwo = response[1].data
const responseThree = response[2].data
})
}
What I'm trying to do is using the every element of arr, making each item's url, and request using axios.all
I think I can simplify the code using loop function such as array.map or other methods. I need some guidance. Thank you.
CodePudding user response:
You can do something like this.
const URL = 'www.hospital.com/diseaseName';
const arr = ['liver', 'heart', 'brain'];
const requests = arr.map((a) => {
return axios.get(URL '?' a);
});
const fetchData = () => {
axios.all( requests )
.then(axios.spread((...response) => {
const responseOne = response[0].data
const responseTwo = response[1].data
const responseThree = response[2].data
})
}