Created
November 6, 2020 01:57
-
-
Save Pacheco95/ac255710aec9bb29c38ac1a6c9e2bba1 to your computer and use it in GitHub Desktop.
A hook to sync URL pagination
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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