How to use the usePagination hook for paginated data in Next.js



Image not found!!

In Next.js, you can use the usePagination hook provided by the swr library to handle paginated data. swr is a React Hooks library for remote data fetching.

Here's a step-by-step guide on how to use the usePagination hook for paginated data in Next.js:

  1. Install SWR: First, you need to install the swr library in your Next.js project. You can do this using npm or yarn:

    bash
    npm install swr # or yarn add swr
  2. Import usePagination Hook: Import the usePagination hook in your component where you want to handle paginated data:

    javascript
    import useSWR, { usePagination } from 'swr';
  3. Fetch Paginated Data: Use the useSWR hook to fetch your paginated data. Pass the pagination parameters (e.g., page number, page size) as query parameters:

    javascript
    const fetcher = (url) => fetch(url).then((res) => res.json()); function MyComponent() { const { data, error } = useSWR('/api/data?page=1&pageSize=10', fetcher); // Handle data and error }
  4. Use usePagination Hook: Use the usePagination hook to control pagination in your component:

    javascript
    function MyComponent() { const { data, error } = useSWR('/api/data?page=1&pageSize=10', fetcher); const { pages, currentPage, setCurrentPage } = usePagination(); if (error) return <div>Error fetching data</div>; if (!data) return <div>Loading...</div>; return ( <div> {/* Display your data */} <ul> {data.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> {/* Pagination controls */} <div> <button onClick={() => setCurrentPage(currentPage - 1)} disabled={currentPage === 1}> Previous </button> <span>Page {currentPage} of {pages}</span> <button onClick={() => setCurrentPage(currentPage + 1)} disabled={currentPage === pages}> Next </button> </div> </div> ); }
  5. Update Data Fetching URL: Update the URL in the useSWR hook based on the current page selected by the user:

    javascript
    const { data, error } = useSWR(`/api/data?page=${currentPage}&pageSize=10`, fetcher);
  6. Handle Pagination Logic: Update the UI and data fetching logic based on the current page selected by the user.

That's it! You've now implemented pagination using the usePagination hook in Next.js with SWR. Make sure to adjust the code according to your specific pagination requirements and API endpoints.