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:
Install SWR: First, you need to install the swr
library in your Next.js project. You can do this using npm or yarn:
bashnpm install swr
# or
yarn add swr
Import usePagination
Hook: Import the usePagination
hook in your component where you want to handle paginated data:
javascriptimport useSWR, { usePagination } from 'swr';
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:
javascriptconst 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
}
Use usePagination
Hook: Use the usePagination
hook to control pagination in your component:
javascriptfunction 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>
);
}
Update Data Fetching URL: Update the URL in the useSWR
hook based on the current page selected by the user:
javascriptconst { data, error } = useSWR(`/api/data?page=${currentPage}&pageSize=10`, fetcher);
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.