Replies: 1 comment 1 reply
-
I implemented server-side pagination recently. Here is a hook that you can use. The only caveat is that it needs to know the count: import { useUrlParams } from "~/hooks";
import { parseNumberFromUrlParam } from "~/utils/http";
export function usePagination(
count: number,
) {
const [params, setParams] = useUrlParams();
const pageSize = parseNumberFromUrlParam(params, "limit", 15);
const offset = parseNumberFromUrlParam(params, "offset", 0);
const pageIndex = Math.floor(offset / pageSize) + 1;
const pageCount = Math.ceil(count / pageSize);
const canPreviousPage = pageIndex > 1;
const canNextPage = pageIndex < Math.ceil(count / pageSize);
const gotoPage = (page: number) => {
setParams({
...Object.fromEntries(params),
offset: (page - 1) * pageSize,
limit: pageSize,
});
};
const previousPage = () => {
gotoPage(pageIndex - 1);
};
const nextPage = () => {
gotoPage(pageIndex + 1);
};
const setPageSize = (pageSize: number) => {
setParams({
offset: 0,
limit: pageSize,
});
};
return {
count,
offset,
pageIndex,
pageCount,
pageSize,
canPreviousPage,
canNextPage,
gotoPage,
nextPage,
previousPage,
setPageSize,
};
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi
I'm trying to implement server-side pagination, and need to use manually controlled pageIndex state (as described here)
If i'm using controlled state, can I still use
usePagination
'scanPreviousPage, canNextPage, gotoPage, nextPage, previousPage
? or do I have to implement those functions by myself?Thanks
Beta Was this translation helpful? Give feedback.
All reactions