To use the useSWRInfinite
hook for paginating data with a custom page size in Next.js, you need to follow these steps:
swr
and axios
for this example.bashnpm install swr axios
javascriptimport useSWRInfinite from 'swr/infinite';
import axios from 'axios';
javascriptconst fetcher = async (url) => {
const res = await axios.get(url);
return res.data;
};
javascriptconst getPageUrl = (pageIndex, pageSize) => {
// Customize this function according to your API endpoint structure
return `https://your-api.com/data?page=${pageIndex}&pageSize=${pageSize}`;
};
useSWRInfinite
hook to fetch paginated data.javascriptconst 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.setSize
function is used to trigger fetching the next page of data when the user clicks the "Load More" button.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.