Arron J. Linton
Arron J. Linton

Reputation: 691

setting state when using a .map function

I think I may running into a callback hell type scenario or this may be an issue with scope. I want setState with allLeagues array once the .map function is finished running. Problem is, when the .map function is done and this.setState({leagueAL: allLeagues)} is ran, the state is set to an empty array. I do not want to run this.setState inside the .map and set it multiple times. Any thoughts on how I can make the data persist into the state?

getLeagueMatches = () => {
            let allLeagues = []
            if(this.state.leagueMatchesInfo != null){
                this.state.leagueMatchesInfo.map((league, id) => {
                    let leagueID = league.league_id;
                    fetch(`https://apifootball.com/api/?action=get_events&from=2017-09-11&to=2017-09-11&league_id=${leagueID}&APIkey=<APIKey>`)
                        .then(res => res.json())
                            .then(event => {
                                //console.log(event)
                                if(event.error){
                                    //console.log(event.error)
                                }else{
                                    league.matches = true;
                                    //console.log(league)
                                    allLeagues = [...allLeagues, league]
                                }
                            })
                            console.log(allLeagues)

                 })
                 this.setState({
                     leagueAL: allLeagues
                 })
            }//end if(65)    
        };//end renderItem

Upvotes: 1

Views: 1997

Answers (2)

Kyle Lussier
Kyle Lussier

Reputation: 112

The issue is that you're not updating the allLeagues array until the promises have resolved. However, setState is being called before any of this even happens.

I would look into something like Promise.all(). Then you can create an array of promises with each call to fetch. Then you can call .then off your Promise.all() and set the state within the .then.

Upvotes: 1

MC10
MC10

Reputation: 572

.map() returns a new array. You'll need to catch it in a variable. In map, you should have a function that does something on each element.

allLeagues = this.state.leagueMatchesInfo.map((league, id) => { ... } this.setState({ leagueAL: allLeagues })

Then setState after the map.

Upvotes: 2

Related Questions