JAVASCRIPT
Fetch and Display Paginated API Data
Learn to fetch and display paginated data from a REST API in a React application. Implement navigation buttons for previous and next pages to enhance user experience.
import React, { useState, useEffect } from 'react';
function PaginatedDataFetcher() {
const [data, setData] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchData = async (page) => {
setLoading(true);
setError(null);
try {
// Replace with your actual API endpoint
const response = await fetch(`https://api.example.com/items?page=${page}&limit=10`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
setData(result.items); // Assuming API returns { items: [], totalPages: N }
setTotalPages(result.totalPages || 1);
setCurrentPage(page);
} catch (e) {
setError('Failed to fetch data. Please try again.');
console.error('Fetching error:', e);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData(currentPage);
}, [currentPage]); // Re-fetch data when currentPage changes
const handleNextPage = () => {
if (currentPage < totalPages) {
setCurrentPage(prev => prev + 1);
}
};
const handlePreviousPage = () => {
if (currentPage > 1) {
setCurrentPage(prev => prev - 1);
}
};
if (loading) return <p>Loading data...</p>;
if (error) return <p style={{ color: 'red' }}>{error}</p>;
return (
<div>
<h1>Paginated Items</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li> // Assuming items have 'id' and 'name'
))}
</ul>
<div>
<button onClick={handlePreviousPage} disabled={currentPage === 1}>
Previous
</button>
<span> Page {currentPage} of {totalPages} </span>
<button onClick={handleNextPage} disabled={currentPage === totalPages}>
Next
</button>
</div>
</div>
);
}
export default PaginatedDataFetcher;
How it works: This React component demonstrates how to fetch and display data from a paginated API endpoint. It manages `currentPage`, `totalPages`, `data`, `loading`, and `error` states. The `useEffect` hook triggers data fetching whenever the `currentPage` changes. Navigation buttons allow users to move between pages, with their disabled states controlled by the current page and total pages count. This pattern is essential for handling large datasets efficiently on the client-side, reducing initial load times and improving user experience.