When I use the method slice()
, I get : "TypeError: Cannot read properties of null (reading 'slice')". Whereas when I remove the method slice()
, the Pokemon cards are rendered as a list. Unfortunately, I do need this method to create a pagination. Is there any equivalent to slice()
? Or am I doing something wrong ?
import React, { Component } from 'react'
import axios from 'axios'
import ReactPaginate from 'react-paginate';
import PokemonCard from './PokemonCard';
export default class PokemonList extends Component {
state = {
url: "https://pokeapi.co/api/v2/pokemon?limit=100000&offset=0",
pokemon: null, // on créé un objet (qui va devenir un tableau) pokemon null c'est où on va enregistrer le json
pageNumber: 1,
pokemonsPerPage: 16
};
async componentDidMount() {
const res = await axios.get(this.state.url);
console.log(res.data['results']);
this.setState({pokemon: res.data['results']});
};
render() {
console.log(this.state.pokemon);
const pagesVisited = this.state.pageNumber * this.state.pokemonsPerPage;
const displayUsers = this.state.pokemon
.slice(pagesVisited, pagesVisited this.state.pokemonsPerPage)
.map((pokemon) => {
return (
<PokemonCard
key={pokemon.name}
name={pokemon.name}
url={pokemon.url}
/>
)
})
return (
<React.Fragment>
{this.state.pokemon ? (
<div className='row'>
{displayUsers}
</div>
) : (<h2>Loading Pokemon</h2>)}
</React.Fragment>
)
}
}
CodePudding user response:
The problem is that in your initial state you set 'pokemon' to null. Method slice() does not exist on 'null'. You should either set 'pokemon' to an empty array in the initial state or add a check that it is not null before slicing.
CodePudding user response:
you just need to set initial state of pokemon to an empty array
Like this:
state = {
url: "https://pokeapi.co/api/v2/pokemon?limit=100000&offset=0",
pokemon: [], // on créé un objet (qui va devenir un tableau) pokemon null c'est où on va enregistrer le json
pageNumber: 1,
pokemonsPerPage: 16
};