Welcome folks today in this blog post we will be looking at an example to fetch data
from jsonplaceholder api
on infinite scroll
and display data in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<div id="root"></div> <script> // Set the initial state let currentPage = 1; let isFetching = false; let hasMore = true; let root = document.getElementById("root"); // Fetch the data from the API async function fetchData() { isFetching = true; let response = await fetch(`https://jsonplaceholder.typicode.com/posts?_page=${currentPage}`); let data = await response.json(); isFetching = false; if (data.length === 0) { hasMore = false; return; } // Render the data for (let post of data) { let div = document.createElement("div"); div.innerHTML = `<h2>${post.title}</h2><p>${post.body}</p>`; root.appendChild(div); } currentPage++; } // Fetch the initial data fetchData(); // Attach the scroll event listener window.addEventListener("scroll", () => { if (isFetching || !hasMore) { return; } if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) { // you're at the bottom of the page fetchData(); } }); </script> |
As you can see we are using the async
and await
to make a simple get
request to the jsonplaceholder
api to fetch the blog posts present at the particular page and displaying at in the browser. And also when the user scroll
down to the bottom to the page we detect that and inside it we are calling the fetchData()
method and inside it we are again calling the jsonplaceholder
api to fetch the next blog
posts. And we are displaying the post
title and body inside the browser.