'why my list have only two items , but it does 20 iterations -REACT

after iteration ,state.pokemons size is two, but the count print between 0 and 19

state = {pokemons:[],};
componentDidMount(){
    let url = "https://pokeapi.co/api/v2/pokemon/";
    fetch(url).then(res=>res.json())
    .then(json=>{
      console.log(json);
      let cont = 0;
      json.results.forEach(el => {
           fetch(el.url)
           .then(res=>res.json())
           .then(json=>{
            cont++;
           // console.log(cont);
             let pokemon = {id:json.id,name:json.name,avatar:json.sprites.front_default}
              let pokemons = [...this.state.pokemons,pokemon];
             this.setState({pokemons});
           });
      });
    });
}

this only show two items in the view

 return (
     <>
     <h2> List size {this.state.pokemons.length}</h2>
     {this.state.pokemons.map(el=><Pokemon key={el.id} name={el.name} avatar={el.avatar} />)}
     </>
 )


Solution 1:[1]

I solved it changed this.setState

  this.setState((previus) => {
            return {
            pokemons: [...previus.pokemons, pokemon]
            }
            })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ayrton Axel