Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 3x 3x 3x 3x 1x 3x 3x 3x 3x | import { useMemo } from "react";
export interface UsePaginationOptions {
limit?: number;
offset?: number;
}
const takePage = <T extends any[]>(
items: T,
opts: Required<UsePaginationOptions>
) => {
const { limit, offset } = opts;
const start = offset * limit;
const stop = start + limit;
return items.slice(start, stop);
};
export const usePagination = <T extends any[]>(
data: T,
options?: UsePaginationOptions
) => {
const { limit = 25, offset = 0 } = options ?? {};
const pageLimit = data ? Math.floor(data.length / limit) : 0;
return useMemo(
() => ({
page: takePage(data, {
limit,
offset: offset > pageLimit ? pageLimit : offset,
}) as T,
pageLimit,
}),
[data, limit, offset, pageLimit]
);
};
|