Skip to content

Commit

Permalink
feat(apps/web): Create useUrlSearchParams custom hook to handle all s…
Browse files Browse the repository at this point in the history
…earch params
  • Loading branch information
nevendyulgerov committed Dec 16, 2024
1 parent c62267f commit a0af3fe
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions apps/web/src/hooks/useUrlSearchParams.ts
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],
);
};

0 comments on commit a0af3fe

Please sign in to comment.