ReactJS not passing updated State

first of all, thank you to Chris G for the hint in the comment.

There’s the problem: a forEach loop doesn’t wait for async code inside, only a for loop does, and you haven’t even used await. When you call this.setState({ pokemon: details.pokemon });, none of the api calls has finished yet, and it’s still [], exactly what causes the behavior you observe.

So here is my solution:

  async loadApi(){
    const temp= await api.get('',{
      params:{
        limit:50,
        offset:showrandom()
      }
    });
    const pokemon=[];
    for(let i=0; i<temp.data.results.length; i++){
      await api.get('/'+temp.data.results[i].name)
      .then(res => pokemon.push(res.data))
    }
    this.setState({pokemon:pokemon});
    return pokemon;
  }
  componentDidMount(){
    this.loadApi();
  }

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top