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



Image not found!!


To use the useSWRInfinite hook for paginating data with a custom page size in Next.js, you need to follow these steps:

  1. Install the required dependencies. You need swr and axios for this example.
bash
npm install swr axios
  1. Import the necessary modules in your Next.js page/component.
javascript
import useSWRInfinite from 'swr/infinite'; import axios from 'axios';
  1. Define a function to fetch data from your API.
javascript
const fetcher = async (url) => { const res = await axios.get(url); return res.data; };
  1. Create a function to generate the API endpoint URLs for each page.
javascript
const getPageUrl = (pageIndex, pageSize) => { // Customize this function according to your API endpoint structure return `https://your-api.com/data?page=${pageIndex}&pageSize=${pageSize}`; };
  1. Use the useSWRInfinite hook to fetch paginated data.
javascript
const MyComponent = () => { const pageSize = 10; // Custom page size const getKey = (pageIndex, previousPageData) => { // When previousPageData is null, it means this is the first page if (previousPageData && !previousPageData.length) return null; // reached the end // Return the next page URL return getPageUrl(pageIndex, pageSize); }; const { data, error, size, setSize, isValidating } = useSWRInfinite(getKey, fetcher); // Flatten the data array (assuming your API returns an array of items) const items = data ? data.reduce((acc, curr) => [...acc, ...curr], []) : []; if (error) return <div>Error fetching data</div>; if (!data) return <div>Loading...</div>; return ( <div> {items.map((item, index) => ( <div key={index}>{/* Render your item here */}</div> ))} <button onClick={() => { setSize(size + 1); }} disabled={isValidating} > {isValidating ? 'Loading...' : 'Load More'} </button> </div> ); }; export default MyComponent;

In this example:

  • getKey function is responsible for generating the URL for each page based on the page index and the previous page data.
  • useSWRInfinite hook manages fetching data for each page and handles caching, revalidating, and pagination automatically.
  • The setSize function is used to trigger fetching the next page of data when the user clicks the "Load More" button.
  • The isValidating flag helps to disable the "Load More" button while the next page data is being fetched to prevent duplicate requests.

Make sure to customize the fetcher function and getPageUrl function according to your API endpoint structure.