0

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.

1 Answer 1

1

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
  })
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much Tirth, I almost spend two hours figuring it out.
No problem @Aden Lee

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.