How to use the useSWRInfinite hook for paginating data with automatic scrolling in Next.js



Image not found!!

To use the useSWRInfinite hook for paginating data with automatic scrolling in a Next.js application, you'll first need to set up your environment with the necessary libraries. useSWRInfinite is part of the swr library, which is a React Hooks library for data fetching. Here's a step-by-step guide:

  1. Install Required Packages: First, ensure you have swr installed in your Next.js project. You can install it via npm or yarn:

    bash
    npm install swr # or yarn add swr
  2. Implementing the Hook: In your Next.js component, import the useSWRInfinite hook and use it to fetch paginated data.

    javascript
    import useSWRInfinite from 'swr'; import { useState } from 'react'; const fetcher = (url) => fetch(url).then((res) => res.json()); function MyComponent() { const [page, setPage] = useState(1); // Track the current page const getKey = (pageIndex, previousPageData) => { if (previousPageData && !previousPageData.length) return null; // reached the end return `/api/data?page=${pageIndex + 1}`; // Adjust URL based on your API structure }; const { data, error, isValidating, mutate } = useSWRInfinite(getKey, fetcher); // Combine all the data from different pages const allData = data ? data.reduce((acc, curr) => [...acc, ...curr], []) : []; // Implement infinite scrolling const handleScroll = (e) => { const { scrollTop, clientHeight, scrollHeight } = e.currentTarget; if (scrollHeight - scrollTop === clientHeight) { setPage((prevPage) => prevPage + 1); } }; // Attach scroll event listener useEffect(() => { window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, []); if (error) return <div>Error fetching data</div>; if (!data) return <div>Loading...</div>; return ( <div> <ul> {allData.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> {isValidating && <div>Loading more...</div>} </div> ); } export default MyComponent;
  3. Explanation:

    • fetcher: This is a function used by swr to fetch data. You can adjust it according to your API structure.
    • getKey: This function generates a unique key for each page request. It's used by swr to cache data based on the page index.
    • useSWRInfinite: This hook fetches data based on the provided key generator function and fetcher function.
    • allData: This variable combines all data fetched from different pages into a single array.
    • handleScroll: This function detects when the user has scrolled to the bottom of the page, indicating the need to fetch more data.
    • useEffect: Attaches and removes the scroll event listener.
    • The component renders the fetched data and displays a loading indicator while data is being fetched.
  4. Adjust API Endpoint: Make sure to replace /api/data?page=${pageIndex + 1} with the correct endpoint for your API.

By following these steps, you'll be able to implement paginated data fetching with automatic scrolling in your Next.js application using the useSWRInfinite hook.