Skip to content

Instantly share code, notes, and snippets.

@Pacheco95
Created November 6, 2020 01:57
Show Gist options
  • Save Pacheco95/ac255710aec9bb29c38ac1a6c9e2bba1 to your computer and use it in GitHub Desktop.
Save Pacheco95/ac255710aec9bb29c38ac1a6c9e2bba1 to your computer and use it in GitHub Desktop.
A hook to sync URL pagination
import React from "react";
function parsePagination() {
const searchParams = new URLSearchParams(window.location.search);
return {
page: parseInt(searchParams.get("page") || 1),
pageSize: parseInt(searchParams.get("pageSize") || 10),
};
}
export const usePagination = () => {
const { page: _page, pageSize: _pageSize } = parsePagination();
const [page, setPage] = React.useState(_page);
const [pageSize, setPageSize] = React.useState(_pageSize);
React.useMemo(() => {
const searchParams = new URLSearchParams(window.location.search);
const newURL = new URL(window.location.href);
searchParams.set("page", page);
searchParams.set("pageSize", pageSize);
searchParams.sort();
newURL.search = searchParams.toString();
window.history.pushState({ path: newURL.href }, "", newURL.href);
console.log({
page, pageSize
})
}, [page, pageSize]);
return {
page,
pageSize,
setPage,
setPageSize,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment