-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(apps/web): Create useUrlSearchParams custom hook to handle all s…
…earch params
- Loading branch information
1 parent
c62267f
commit a0af3fe
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import { usePathname, useRouter, useSearchParams } from "next/navigation"; | ||
import { pathOr } from "ramda"; | ||
import { useCallback, useMemo } from "react"; | ||
|
||
export const limitBounds = { | ||
"10": 10, | ||
"20": 20, | ||
"30": 30, | ||
} as const; | ||
|
||
export type LimitBound = (typeof limitBounds)[keyof typeof limitBounds]; | ||
|
||
export type UsePaginationReturn = [ | ||
{ limit: LimitBound; page: number; query: string }, | ||
(page: number, limit: LimitBound, query: string) => void, | ||
]; | ||
|
||
export const useUrlSearchParams = (): UsePaginationReturn => { | ||
const searchParams = useSearchParams(); | ||
const router = useRouter(); | ||
const pathName = usePathname(); | ||
const urlSearchParams = new URLSearchParams(searchParams); | ||
const pg = parseInt(urlSearchParams.get("pg") ?? ""); | ||
const lt = urlSearchParams.get("lt") ?? limitBounds[10]; | ||
const limit = pathOr(limitBounds[10], [lt], limitBounds); | ||
const page = isNaN(pg) ? 1 : pg; | ||
const query = urlSearchParams.get("query") ?? ""; | ||
|
||
const updateParams = useCallback( | ||
(page: number, limit: number, query: string): void => { | ||
const urlSearchParams = new URLSearchParams({ | ||
query: query.toString(), | ||
pg: page.toString(), | ||
lt: limit.toString(), | ||
}); | ||
|
||
router.push(`${pathName}?${urlSearchParams.toString()}`, { | ||
scroll: false, | ||
}); | ||
}, | ||
[router, pathName], | ||
); | ||
|
||
return useMemo( | ||
() => [{ page, limit, query }, updateParams], | ||
[page, limit, query, updateParams], | ||
); | ||
}; |