How to fetch next pages until they run out

Asked

Viewed 35 times

-1

Good afternoon. I have the following code

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

class App extends Component {
  constructor(){
    super();
    this.state={
      pokemonList : [],
      count : 0,
      next : "",
      previous : null
    }
  }

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

  render (){
    const {pokemonList} = this.state;
    let number = 1;
    return(
      <div className="container">
        <header>
          <h1>Pokédex</h1>
        </header>
        <h1>
          {pokemonList.map(pkmn => 
            <div className="jumbotron" key={pkmn.name}>
              <h1 class="first">{number++}</h1> 
              <h1 class="second">{pkmn.name}</h1>
            </div>
          )}
        </h1>
      </div>
    )
  };
}

export default App;

If you look at the API, it has the values of next and Previous. I would like to know how to import all these values at once, and not just import the top twenty.

1 answer

1

By checking the next link of the API you placed, I received the following URL:

https://pokeapi.co/api/v2/pokemon?offset=20&limit=20

That is, it is possible to pass two parameters via GET which mean the following:

  • offset: How many entries should "jump". For example, if I put offset=40, it will return from the result 41;
  • limit: Limits how many results will come on a page, that is, if I put limit=20, it will bring a vector with 20 objects;

To solve your problem just set a very high value to the limit, for example, if you try to access the API as follows: https://pokeapi.co/api/v2/pokemon?limit=1000, He’ll bring all the objects. It is important to remember that this can make your application take longer to load, since you will have to load a much larger amount of objects and for that there is the offset and the limit.

Browser other questions tagged

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