Deivbid
Deivbid

Reputation: 403

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

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:

Look, Even the item is changing (those tt....) I always get the last responde, what can I do ?

Upvotes: 6

Views: 2787

Answers (3)

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

Upvotes: 4

Tiago Alves
Tiago Alves

Reputation: 2316

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

Upvotes: 1

r.delic
r.delic

Reputation: 863

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

Upvotes: 0

Related Questions