I'm having a problem making multiple request in a loop.
I'm making a react app that renders multiple components called Cards. inside each card I want to make some requests so I got this.
componentWillMount(){
if(this.props.movies){
let promises = []
this.props.movies.forEach((item, i) => {
console.log(item)
let movieUrl = `http://localhost:3000/movies/${item}`
promises.push(axios.get(movieUrl))
})
axios.all(promises).then(res => console.log(res))
}
}
Movies is an array that I get from the father component. so apparently is working because I get results but tit is always with the last element of the last card. Here is an image:
Since axios returns a Promise we can go for multiple requests by using Promise. all , luckily axios itself also ships with a function called all , so let us use that instead and add two more requests. Again we define the different URLs we want to access. const requestOne = axios.
all is a helper method built into Axios to deal with concurrent requests. Instead of making multiple HTTP requests individually, the axios. all method allows us to make multiple HTTP requests to our endpoints altogether.
Axios Get Request get() method is used to make an HTTP get request. There are two parameters that must be passed to the Axios get() method. It first requires the service endpoint's URI. Second, an object containing the properties we wish to send to our server API should be supplied to it.
To send data, fetch() uses the body property for a post request to send data to the endpoint, while Axios uses the data property. The data in fetch() is transformed to a string using the JSON. stringify method.
You should avoid using forEach
when you really need to map
and build the url with item.imdbID
instead of item
componentWillMount(){
if(this.props.movies){
const promises = this.props.movies.map(item => {
const movieUrl = `http://localhost:3000/movies/${item.imdbID}`
console.log(movieUrl)
return axios.get(movieUrl)
)
Promise.all(promises).then(results => console.log(results))
}
}
Edit1: removed async/await due to incompatible build configuraton
Edit2: used item.imdbID
instead of item
and logged urls
You can use async/await
. Look:
async componentWillMount(){
if(this.props.movies){
const results = []
this.props.movies.forEach((item, i) => {
const movieUrl = `http://localhost:3000/movies/${item}`
const result = await axios.get(movieUrl)
results.push(result)
})
// console.log(results)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With