Details of what I am trying to achieve:
Fetch data from Pokemon API and render a few pokemons (response from API is NAME & URL of the Pokemon which leads to an end point with details about that Pokemon. I was able to fetch and receive a response which is currently being rendered on the page using the
array.map()
method in the form of<li>
components.Created a click event on each
<li>
to return the index of that element. The goal is to pass this index to another component where another fetch request is being made based on the index of this element. E.g. if user clicks Pokemon "A" then I am hitting the API with "A" to retrieve Pokemon "A" details back and render the on to the page.
My issue is that the onClick function isn't performing correctly. I have to hit the <li> Pokemon </li>
twice to get the index of that element.
class PokemonList extends Component {
constructor () {
super();
this.state = {
currPoke: null,
}
}
pokeClicked(index){
console.log('poke got clicked-->', this.state.currPoke);
this.setState({
currPoke: index+1,
})
console.log('after set state', this.state.currPoke);
}
render () {
return(
<div className="list">
<ul>
{this.props.apiData.map((p, index) => {
return <li onClick={()=>{this.pokeClicked(index)}} key={index}>{p.name.charAt(0).toUpperCase() + p.name.slice(1)}</li>
})}
</ul>
<div className="lis">
{this.renderClickedPoke()}
</div>
</div>
)
}