What is the best way to make multiple get request with axios in a loop? What is the best way to make multiple get request with axios in a loop? reactjs reactjs

What is the best way to make multiple get request with axios in a loop?


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 configuratonEdit2: 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)    }}


Have you tried using bluebird's Promise.mapSeries?

import Promise from 'bluebird'componentWillMount(){    if(this.props.movies){         Promise.resolve(this.props.movies)            .mapSeries(item => axios.get(`http://localhost:3000/movies/${item}`))            .then(movies => console.log(movies))    }}