To use the useSWRInfinite
hook for paginated data fetching in Next.js, you'll first need to install the swr
package if you haven't already:
bashnpm install swr
# or
yarn add swr
Then, you can follow these steps:
Import the useSWRInfinite
hook:
Import the useSWRInfinite
hook from the swr
package in your Next.js component file:
javascriptimport useSWRInfinite from 'swr/infinite';
Define a function to fetch data:
Create a function that will be responsible for fetching paginated data. This function should accept a pageIndex
parameter, which will be used to determine which page of data to fetch.
javascriptconst fetcher = async (url) => {
const response = await fetch(url);
return response.json();
};
Use useSWRInfinite
hook:
Inside your Next.js component, use the useSWRInfinite
hook passing in your fetch function and any other options you need.
javascriptconst MyComponent = () => {
const PAGE_SIZE = 10;
const getKey = (pageIndex, previousPageData) => {
if (previousPageData && !previousPageData.length) return null; // reached the end
return `/api/data?page=${pageIndex + 1}&pageSize=${PAGE_SIZE}`;
};
const { data, error, size, setSize } = useSWRInfinite(getKey, fetcher);
// Render your component using the `data` array
// Handle loading and error states
return (
// Your component JSX
);
};
Handle pagination:
Inside your component, handle how you want to display and interact with the paginated data. Typically, you'll have some UI elements like buttons or a scroll event listener to trigger fetching more data when the user reaches the end of the current data set.
You can use the size
and setSize
values returned by useSWRInfinite
to keep track of the current page and load more data.
javascriptconst handleLoadMore = () => {
setSize(size + 1);
};
You can trigger handleLoadMore
based on user interaction, such as clicking a "Load More" button or reaching the end of a scroll container.
Render the data:
Render the data fetched by useSWRInfinite
inside your component based on your UI requirements.
javascriptreturn (
<div>
{data.map((pageData, index) => (
<ul key={index}>
{pageData.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
))}
<button onClick={handleLoadMore}>Load More</button>
</div>
);
This will render each page of data as a separate list and provide a "Load More" button to fetch the next page.
That's a basic overview of how to use the useSWRInfinite
hook for paginated data fetching in Next.js. You can customize it further based on your specific use case and UI requirements.