2021-07-07 11:04:36 +02:00
|
|
|
import { useEffect, useState } from 'react';
|
2022-05-04 08:14:49 +02:00
|
|
|
import { paginate } from 'utils/paginate';
|
2021-07-07 11:04:36 +02:00
|
|
|
|
2022-05-05 15:34:46 +02:00
|
|
|
/**
|
|
|
|
* @deprecated
|
|
|
|
*/
|
2022-05-04 08:14:49 +02:00
|
|
|
const usePagination = <T>(
|
|
|
|
data: T[],
|
2022-01-26 12:27:34 +01:00
|
|
|
limit: number,
|
2022-05-04 08:14:49 +02:00
|
|
|
filterFunc?: (item: T) => boolean
|
2022-01-26 12:27:34 +01:00
|
|
|
) => {
|
2022-05-04 08:14:49 +02:00
|
|
|
const [paginatedData, setPaginatedData] = useState<T[][]>([[]]);
|
2021-07-07 11:04:36 +02:00
|
|
|
const [pageIndex, setPageIndex] = useState(0);
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-01-26 12:27:34 +01:00
|
|
|
let dataToPaginate = data;
|
|
|
|
|
|
|
|
if (filterFunc) {
|
|
|
|
dataToPaginate = data.filter(filterFunc);
|
|
|
|
}
|
|
|
|
|
|
|
|
const result = paginate(dataToPaginate, limit);
|
2022-05-19 14:27:19 +02:00
|
|
|
setPageIndex(0);
|
2021-07-07 11:04:36 +02:00
|
|
|
setPaginatedData(result);
|
2022-01-26 12:27:34 +01:00
|
|
|
/* eslint-disable-next-line */
|
2022-02-09 12:25:02 +01:00
|
|
|
}, [JSON.stringify(data), limit]);
|
2021-07-07 11:04:36 +02:00
|
|
|
|
|
|
|
const nextPage = () => {
|
|
|
|
if (pageIndex < paginatedData.length - 1) {
|
|
|
|
setPageIndex(prev => prev + 1);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const prevPage = () => {
|
|
|
|
if (pageIndex > 0) {
|
|
|
|
setPageIndex(prev => prev - 1);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const lastPage = () => {
|
|
|
|
setPageIndex(paginatedData.length - 1);
|
|
|
|
};
|
|
|
|
|
|
|
|
const firstPage = () => {
|
|
|
|
setPageIndex(0);
|
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
page: paginatedData[pageIndex] || [],
|
|
|
|
pages: paginatedData,
|
|
|
|
nextPage,
|
|
|
|
prevPage,
|
|
|
|
lastPage,
|
|
|
|
firstPage,
|
|
|
|
setPageIndex,
|
|
|
|
pageIndex,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default usePagination;
|