Separating API data on different pages

I am using JavaScript with Rails to get API data from PokeAPI. My goal is to have the data spread across different pages, but I am not sure how to separate my API data so that some appears on one page and some appears on another.

For example, in my fetchPokemon function below, it iterates over 1-151 and displays the data. However, I want 152-251 on a different page, and then a different set of ids displayed on another page etc.

Here’s my code that pulls the data from the API.

//Sets API id limit
const dex_id = 151;

//Variable to iterate over API data
const fetchPokemon = async () => {
    for (let i = 1; i<= dex_id; i++) {
      await getPokemon(i);

//Gathers data from API
  const getPokemon = async id => {
    const url = `${id}`;
    const res = await fetch(url);
    const pokemon = await res.json();



Would I just need to make a function similar to fetchPokemon but with a for loop with the appropriate numbers? And how could I get only that function to show on a specific page?

If you’re using Rails, why are you pulling the datums one by one from the API using JS? Why not get all the data server-side in Rails then put them in the shape you want for the frontend to grab? I’m not quite sure the point of using Rails if you do what you’re doing, it could just be a static HTML page.

Like here:

So if you use the Ruby wrapper, you can call any endpoint and specify the pagination limit and it’ll return a list of entries + a URL for the next set of entries

Then you can just serve that (I assume as JSON) for the front end however you want, and in the JS just run fetch to get first page, fetch to get second page etc etc (though not sure there’s any point complicating things this way as there are several libraries that will give you similar results without using JS [Turbolinks or StimulusReflex for example])

I had some issues using API gems and there are a lot of resources for using PokeAPI with JavaScript so I decided to do it that way to help improve my JavaScript skills. Though you’re right that there’s no real reason to do it in Rails, I just typically default to my Rails boilerplate when working on projects in case I want to expand upon it.

I’d still like to know how to separate the API data across different pages via JavaScript for my personal knowledge and in the future if I do something similar.

You shouldn’t be pulling every single datum individually, the API lets you request paginated data, and you can specify how much of that you want. It also returns the URL for the next set of data based on the original parameters (so if you ask for a hundred, it will give you those along with the URL to the next hundred and so on).

It’s easier to use the JS client wrapper rather than writing the logic yourself:

But if you are writing it yourself, look at that repo to see how it is done, as your logic will be identical