Skip to content

Instantly share code, notes, and snippets.

@heyolajyd
Created May 23, 2020 01:48
Show Gist options
  • Save heyolajyd/aae3cd3e28d9069147bfc562ba4e8561 to your computer and use it in GitHub Desktop.
Save heyolajyd/aae3cd3e28d9069147bfc562ba4e8561 to your computer and use it in GitHub Desktop.
Simple Pagination
import React, { useEffect, useState, useCallback } from 'react';
const USERS_URL = 'https://example.com/api/users';
const PAGE_SIZE = 10;
const calcPageCount = (count) => {
return Math.floor(count/PAGE_SIZE) + (count%PAGE_SIZE ? 1 : 0);
}
export default function Table () {
const [isLoading, setIsLoading] = useState(false);
const [users, setUsers] = useState([]);
const [totalCount, setTotalCount] = useState(0);
const [pageCount, setPageCount] = useState(0);
const [currentPage, setCurrentPage]= useState(0);
const fetchUsers = useCallback(async (page) => {
setIsLoading(true);
let response = await fetch(`${USERS_URL}?page=${page}`);
const { count, results} = await response.json();
setUsers(results);
setTotalCount(count);
setPageCount(calcPageCount(count));
setIsLoading(false);
}, []);
useEffect(() => {
fetchUsers(0);
}, [fetchUsers]);
const goToPage = (page) => {
fetchUsers(page);
setCurrentPage(page)
}
const handleNext = () => {
fetchUsers(currentPage + 1);
setCurrentPage(prev => prev + 1);
}
const handlePrev = () => {
fetchUsers(currentPage - 1);
setCurrentPage(prev => prev - 1);
}
const lastPage = pageCount - 1;
return (
<div>
<table className="table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
{users.map(({ firstName, lastName, id }) => {
return (
<tr key={id}>
<td>{id}</td>
<td>{firstName}</td>
<td>{lastName}</td>
</tr>
)
})}
</tbody>
</table>
<section className="pagination">
<button disabled={isLoading} className="first-page-btn" onClick={() => goToPage(0)}>first</button>
<button disabled={isLoading || currentPage < 1} className="previous-page-btn"onClick={handlePrev}>previous</button>
<button disabled={isLoading || currentPage >= lastPage} className="next-page-btn" onClick={handleNext}>next</button>
<button disabled={isLoading} className="last-page-btn"onClick={() => goToPage(lastPage)}>last</button>
</section>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment