Completely new to React and I'm building a small Pokedex based on Pokeapi. I'm able to fetch Pokemon, its corresponding data, render it successfully.
I'm having a dropdown wherein the users can select the Pokemon range (start and end no.) and the Pokemon list should update automatically. The problem is, the previous range is not getting cleared and the current range is added with the previous range. But when I allow all the Pokemon in a range to load completely and select the second range, I'm not facing this error. Quickly toggling between the ranges causes this error. Code snippets below.
The thing is allPokemons is getting set to empty when I select a dropdown item, but the same isn't reflecting in the render
GIF demonstrating my issue : Pokedex error
Codesandbox link : here
State:
constructor(props) {
super(props);
this.state = {
allPokemons: [],
limit: 151,
offset: 0,
regions: [
{
name: "Kanto",
limit: 151,
offset: 0,
},
{
name: "Johto",
limit: 100,
offset: 151,
},
]
}
}
Fetching Pokemon list and corresponding data:
getAllPokemons = async () => {
const response = await axios.get(`https://pokeapi.co/api/v2/pokemon?limit=${this.state.limit}&offset=${this.state.offset}`).catch((err) => console.log("Error:", err));
this.getPokemonData(response.data.results);
}
getPokemonData = async (result) => {
this.setState({
allPokemons : [],
})
var response;
for (var i = 0; i < result.length; i++) {
response = await axios.get(`https://pokeapi.co/api/v2/pokemon/${result[i].name}`).catch((err) => console.log("Error:", err));
this.setState({
allPokemons: [...this.state.allPokemons,response.data],
})
}
}
Dropdown handle change function
handleChangeRegions = (event) => {
this.setState({
allPokemons : [],
})
for (var i = 0; i < this.state.regions.length; i++) {
if (this.state.regions[i].name === event.target.value) {
this.setState({
limit : this.state.regions[i].limit,
offset : this.state.regions[i].offset,
allPokemons : [],
},()=>{
this.getAllPokemons();
})
break;
}
}
}
Render component
Object.keys(this.state.allPokemons).map((item, index) =>
<Pokemon
key={index}
id={this.state.allPokemons[item].id}
name={this.state.allPokemons[item].name}
type={this.state.allPokemons[item].types}
/>
)
Dropdown component
<select value={this.state.valueregion} onChange={this.handleChangeRegions}>
{this.state.regions.map((region) => (
<option value={region.name}>{region.name} ({region.offset + 1}-{region.limit + region.offset})</option>
))}
</select>
I need to know the reason for this issue and solutions are much appreciated!