Typeerror: pokemonList.map is not a Function

Asked

Viewed 830 times

1

Good afternoon. I have the following code snippet:

import React,{Component} from 'react';
import './App.css';

class App extends Component {
    constructor(){
    super();
    this.state={
      pokemonList : []
    }
  }

  componentDidMount(){
    fetch("https://pokeapi.co/api/v2/pokemon")
      .then(response => response.json())
      .then(data => this.setState({pokemonList: data}))
  }

  render (){
    const pokemonList = this.state;
    return(
      <div>
        <h1>{pokemonList.map(pkmn => <div>{pkmn.name}</div>)}</h1>
      </div>
    )
  };
}

export default App;

Which results in the error presented in the description of the question. Does anyone know the cause?

1 answer

2


View the data that this API is returning. The return has the following format:

{
  count: number,
  next: string | null,
  previous: string | null,
  results: {
      name: string,
      url: string
  }[]
}

You should be invoking the method map on the property results. Another detail is that you initialized the variable pokemonList with the value of this.state, and not this.state.pokemonList

The code should be like this:

componentDidMount() {
  fetch("https://pokeapi.co/api/v2/pokemon")
    .then(response => response.json())
    .then(data => this.setState({pokemonList: data.results}))
}

render () {
  const {pokemonList} = this.state;
  return( 
    <div>
      <h1>{pokemonList.map(pkmn => <div key={pkmn.name}>{pkmn.name}</div>)}</h1>
    </div>
  )
};

Of course, it would also be interesting you save in your state the values of count, next and previous.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.