To use the useSWRInfinite
hook for paginating data with a custom loading indicator in a Next.js application, you can follow these steps:
swr
if you haven't already:bashnpm install swr
# or
yarn add swr
useSWRInfinite
hook in your Next.js component:javascriptimport useSWRInfinite from 'swr/infinite';
useSWRInfinite
hook in your component:javascriptimport { 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;
Replace fetcher
function with your actual data fetching function. In the example above, it assumes the API endpoint returns data in JSON format.
Customize the loading indicator as per your requirement. In the example above, it shows a simple "Loading more..." text.
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.