How to use the useSWRInfinite hook for paginating data with a custom loading indicator in Next.js



Image not found!!

To use the useSWRInfinite hook for paginating data with a custom loading indicator in a Next.js application, you can follow these steps:

  1. Install swr if you haven't already:
bash
npm install swr # or yarn add swr
  1. Import useSWRInfinite hook in your Next.js component:
javascript
import useSWRInfinite from 'swr/infinite';
  1. Implement the useSWRInfinite hook in your component:
javascript
import { useState } from 'react'; import useSWRInfinite from 'swr/infinite'; const fetcher = async (url) => { const response = await fetch(url); return response.json(); }; const PAGE_SIZE = 10; const MyComponent = () => { const [isLoadingMore, setIsLoadingMore] = useState(false); const getKey = (pageIndex, previousPageData) => { if (previousPageData && !previousPageData.length) return null; // reached the end return `/api/data?page=${pageIndex}&limit=${PAGE_SIZE}`; }; const { data, error, size, setSize } = useSWRInfinite(getKey, fetcher); const items = data ? [].concat(...data) : []; const loadMore = () => { setIsLoadingMore(true); setSize(size + 1); setIsLoadingMore(false); }; return ( <div> {items.map((item, index) => ( <div key={index}>{/* Render your item here */}</div> ))} {isLoadingMore && <div>Loading more...</div>} <button onClick={loadMore} disabled={isLoadingMore}> Load More </button> </div> ); }; export default MyComponent;
  1. Replace fetcher function with your actual data fetching function. In the example above, it assumes the API endpoint returns data in JSON format.

  2. Customize the loading indicator as per your requirement. In the example above, it shows a simple "Loading more..." text.

  3. Adjust PAGE_SIZE constant according to your pagination needs.

This setup will paginate your data using useSWRInfinite hook in Next.js with a custom loading indicator.