How do i paginate data that i fetch from an API

I am fetching data from a real estate API.It is an array of houses for sale.This array has 50 items but I want to display only first 10 of them in the UI so that later on i can add buttons for next and previous pagination.I am getting undefined in the UI.


<!--Property container-->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-4 gap-y-8 p-3" id="property-container">


const properties = document.querySelector("#property-container");
let arrayList = [];
let page = 0;

//Fetch data from an API

document.addEventListener("DOMContentLoaded", sanFranciscoProperties);

function sanFranciscoProperties() {
      method: "GET",
      headers: {
        "x-rapidapi-host": "",
        "x-rapidapi-key": "My_API_Key",
    .then((res) => {
      return res.json();
    .then((response) => {
    .catch((err) => {

//Create div card for each house and fill it with API data

function propertiesForSale(homes) {
  let output = "";

  for (let i = 1; i <= 50; i++) { => {
      let image = home.thumbnail ? home.thumbnail : "image-not-found.png";
      let beds = home.beds ? home.beds : 0;
      let baths = home.baths ? home.baths : 0;

      output += `
      <div class="h-64 px-2 py-2 border-1 border-black mt-4 mb-12">
      <p class="font-sans text-xs text-gray-600 mb-1">Brokered by ${}</p>
      <a href="${home.rdc_web_url}" class="toggle-image" data-id="${}">
      <img src=${image}
      class="w-full h-full"></img>
      <p class="font-sans text-sm mt-2"><span class="ml-3">For Sale</span> <span class="font-semibold text-lg">$${home.price}</span></p>
      <p class="font-sans text-sm"><span class="ml-3 font-semibold">${beds}</span> bed   <span class="font-semibold">${baths}</span> bath</p>
      <p class="font-sans text-sm"><span class="ml-3">${home.address.line}</span>
       <span class="ml-3">${}</span>, <span>${home.address.state_code}</span> <span>${home.address.postal_code}</span>
    arrayList = arrayList.concat(output);

//Display first ten houses in UI

function showFirstTen() {
  let output = "";
  for (let i = 0; i < page + 10; i++) {
    output += arrayList[i];
  properties.innerHTML = output;


I guess you should call showFirstTen() in .then after propertiesForSale(response)

Thanks, I can see my items in the UI now, it s just that i am not getting 10 of them but a lot more.And they seem to be repeating themselves.I guess i made mistake with the for loop somewhere, it s just that I can t figure out what it is.

It’s because you’re looping over results and creating a card for each result. And you’re doing it 50 times in a loop :slight_smile:

1 Like