Pagination.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { useMemo, useState } from 'react';
  2. import { stableSort, getComparator } from '../utils/Sort';
  3. export const usePaginationHook = (list: any[]) => {
  4. const [currentPage, setCurrentPage] = useState(0);
  5. const [pageSize, setPageSize] = useState(10);
  6. const [orderBy, setOrderBy] = useState('');
  7. const [order, setOrder] = useState<'asc' | 'desc'>('asc');
  8. const total = list.length;
  9. const { data, offset } = useMemo(() => {
  10. const offset = pageSize * currentPage;
  11. // only when user click sort, orderBy will have value
  12. const sortList = orderBy
  13. ? stableSort(list, getComparator(order || 'asc', orderBy))
  14. : list;
  15. const data = sortList.slice(offset, offset + pageSize);
  16. return {
  17. offset,
  18. data,
  19. };
  20. }, [pageSize, currentPage, orderBy, list, order]);
  21. const handleCurrentPage = (page: number) => {
  22. setCurrentPage(page);
  23. };
  24. const handlePageSize = (size: number) => {
  25. setPageSize(size);
  26. };
  27. const handleGridSort = (e: any, property: string) => {
  28. const isAsc = orderBy === property && order === 'asc';
  29. setOrder(isAsc ? 'desc' : 'asc');
  30. setOrderBy(property);
  31. };
  32. return {
  33. offset,
  34. currentPage,
  35. pageSize,
  36. handlePageSize,
  37. handleCurrentPage,
  38. total,
  39. data,
  40. handleGridSort,
  41. orderBy,
  42. order,
  43. };
  44. };