File size: 978 Bytes
1e92f2d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import { useMemo } from 'react';
interface PaginationResult< PaginationItem > {
paginatedItems: PaginationItem[];
totalPages: number;
totalItems: number;
currentPage: number;
hasNextPage: boolean;
hasPreviousPage: boolean;
}
function calculatePagination< PaginationItem >(
items: PaginationItem[],
page: number,
perPage: number
): PaginationResult< PaginationItem > {
const startIndex = ( page - 1 ) * perPage;
const paginatedItems = items.slice( startIndex, startIndex + perPage );
const totalItems = items.length;
const totalPages = Math.ceil( totalItems / perPage );
return {
paginatedItems,
totalPages,
totalItems,
currentPage: page,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1,
};
}
export function usePagination< PaginationItem >(
items: PaginationItem[],
page: number,
perPage: number
): PaginationResult< PaginationItem > {
return useMemo( () => calculatePagination( items, page, perPage ), [ items, page, perPage ] );
}
|