Pagination is a technique used to divide a large dataset into smaller, manageable chunks or pages. Here's a step-by-step guide to implementing pagination both on the server side and the client side.
Server-Side Pagination
1. Database Query
First, modify your database query to support pagination. This typically involves using the LIMIT
and OFFSET
clauses (for SQL databases) or their equivalents.
Example for SQL:
-- Fetch records for page 1 with 10 records per page
SELECT * FROM your_table
ORDER BY id
LIMIT 10 OFFSET 0; -- OFFSET = (page_number - 1) * page_size
Example for MongoDB:
db.your_collection.find()
.sort({ _id: 1 })
.skip(0) // Skip the records for previous pages
.limit(10); // Limit to records for the current page
Parameters:
LIMIT
(orlimit
in MongoDB): Number of records per page.OFFSET
(orskip
in MongoDB): Number of records to skip, calculated as(page_number - 1) * page_size
.
2. API Endpoint
Design your API endpoint to accept pagination parameters. These parameters are usually page
and pageSize
or limit
and offset
.
Example in Express (Node.js):
app.get('/data', async (req, res) => { const page = parseInt(req.query.page) || 1;
const pageSize = parseInt(req.query.pageSize) || 10;
const offset = (page - 1) * pageSize;
const data = await db.collection('your_collection')
.find()
.sort({ _id: 1 })
.skip(offset)
.limit(pageSize)
.toArray();
const totalRecords = await db.collection('your_collection').countDocuments();
res.json({
data,
page,
pageSize,
totalRecords,
totalPages: Math.ceil(totalRecords / pageSize)
});
});
3. Handle Pagination in Frontend
Fetch paginated data from the API and handle pagination in your frontend application.
Example using Fetch API:
async function fetchPage(page = 1, pageSize = 10) { const response = await fetch(`/data?page=${page}&pageSize=${pageSize}`);
const result = await response.json();
return result;
}
Client-Side Pagination
1. Display Paginated Data
Render the data on the frontend and provide controls for pagination.
Example in React:
import React, { useState, useEffect } from 'react';
function PaginatedList() {
const [data, setData] = useState([]);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [totalPages, setTotalPages] = useState(0);
useEffect(() => {
async function fetchData() {
const result = await fetchPage(page, pageSize);
setData(result.data);
setTotalPages(result.totalPages);
}
fetchData();
}, [page, pageSize]);
return (
<div>
<ul>
{data.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
<div>
<button onClick={() => setPage(page - 1)} disabled={page <= 1}>Previous</button>
<button onClick={() => setPage(page + 1)} disabled={page >= totalPages}>Next</button>
</div>
</div>
);
}
2. Handle Pagination Controls
Provide UI controls to navigate between pages and update the current page.
Example Controls:
<button onClick={() => setPage(page - 1)} disabled={page <= 1}>Previous</button><button onClick={() => setPage(page + 1)} disabled={page >= totalPages}>Next</button>
Summary
Server-Side:
- Modify database queries to support pagination.
- Create API endpoints that accept pagination parameters.
Client-Side:
- Fetch paginated data from the server.
- Render data and handle pagination controls.
By following these steps, you can efficiently manage large datasets and improve both server performance and user experience.
Social Plugin