nextjs infinite scrolling in typescript without libraries in typescript

To implement infinite scrolling in Next.js with TypeScript, we can use Intersection Observer API, which will trigger a callback function when the user scrolls to the bottom of the page.

First, we will create a new state variable in our React component to keep track of the data we want to load on scroll.

index.ts
import { useState, useEffect } from "react";

type Data = {
  id: number;
  name: string;
  //...
};

const MyComponent = () => {
  const [data, setData] = useState<Data[]>([]);
  const [page, setPage] = useState<number>(1);

  useEffect(() => {
    // Fetch initial data when component mounts
    fetchData();
  }, []);

  const fetchData = async () => {
    const res = await fetch(`https://example.com/api/data?page=${page}`);
    const newData = await res.json();
    setData([...data, ...newData]);
    setPage(page + 1);
  };

  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
      <div id="observer" />
    </ul>
  );
};
680 chars
34 lines

In the code above, we fetch data from the server using the page state variable to retrieve the correct page of data. We then use the spread operator to concatenate the new data with the existing data state. Finally, we increment the page counter.

We added an empty div element with id="observer". This will serve as a marker for the Intersection Observer API. When the user scrolls down to this div, we will trigger the fetchData() function to fetch and display the next set of data.

We can now create the Intersection Observer API and pass it the fetchData function as its callback.

index.ts
const MyComponent = () => {
  // ...

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          fetchData();
        }
      },
      { threshold: 1 }
    );
    // Attach observer to the empty div with id="observer"
    observer.observe(document.querySelector("#observer") as Element);
    return () => observer.disconnect();
  }, []);

  // ...
}
430 chars
20 lines

In the code above, we create a new IntersectionObserver object and pass it a callback function as its first argument.

This callback function takes an entries array as its argument, which contains information about which elements are intersecting with the viewport (in our case, the div element with id="observer").

If the first element in the entries array is intersecting, we call fetch data function to load additional data.

We set the threshold option to 1, which means that the callback will be called as soon as the observer element enters the viewport.

Finally, we attach the observer to the div element with id="observer", and use a cleanup function to remove the observer when the component is unmounted.

This is how you can implement infinite scrolling without using any library in Next.js with TypeScript.

gistlibby LogSnag