Search code examples
javascriptlimitoffset

Implement Pagination in JavaScript with limit and offset


I have a huge data being returned from a fetch api call. I want to limit the displayed data to 10 per page and have more data returned when the next page button is clicked. How can I implement that?

limit is set to 10 and offset is set to 0. The maximum data that can be returned per page is 150.


<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class = B1 id="photos">View photos</button>
<div id="showResults"></div>
<div>
  <nav aria-label="Page navigation example">
    <ul class="pagination">
     
      <li class="page-item">
        <button class="page-link" id="nextButton">Next</button>
      </li>
    </ul>
  </nav>
</div>

<script> 
let limit = 10;
let offset = 0;
const showPhoto = (key, value) => {
 const pre_x = document.createElement("pre");
 const dt_x = document.createElement("dt");
 const dd_x = document.createElement("dd")
 dt_x.textContent = key;
 pre_x.appendChild(dt_x);

  {
      dd_x.textContent = value;
   }
   pre_x.appendChild(dd_x);
 return pre_x;
};

const structurePhotos = (obj) => {
 const dl = document.createElement("dl");
 for (let k in obj) {
   let j = obj[k];
   if (typeof obj[k] === "object") {
     j = JSON.stringify(obj[k], null, 2);
   }
dl.appendChild(showPhoto(k, j));
  }
 return dl;
};


function getPhotos(url) {
 fetch(url)
   .then((res) => (res.ok ? res.json() : Promise.reject(res)))
   .then((data) => {

     if (Array.isArray(data)) {
       data.forEach((photo) => {
         showResults.append(
          structurePhotos(photo),
         );
       });
     } 
   })
   .catch(console.error);
}

const photos = document.getElementById("photos");
photos.addEventListener(
 "onclick",
 getPhotos(`https://jsonplaceholder.typicode.com/photos`)
);

</script>

</body>

</html>

limit is set to 10 and offset is set to 0. The maximum data that can be returned per page is 150.


Solution

    • Use Javascript built-in array function slice()

    • For Ex:

      let fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango", "Banana", "Orange", "Lemon", "Apple", "Mango"];
      fruits.slice(0, 3);     // 0 => offset, 3 => limit
      
    • output

      output => [Banana,Orange,Lemon]