1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-01 00:08:27 +01:00
unleash.unleash/frontend/src/hooks/usePagination.ts

57 lines
1.2 KiB
TypeScript
Raw Normal View History

import { useEffect, useState } from 'react';
import { paginate } from '../utils/paginate';
2022-01-26 12:27:34 +01:00
const usePagination = (
data: any[],
limit: number,
filterFunc?: (item: any) => boolean
) => {
const [paginatedData, setPaginatedData] = useState([[]]);
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);
setPaginatedData(result);
2022-01-26 12:27:34 +01:00
/* eslint-disable-next-line */
}, [data, limit]);
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;