Skip to content

Commit

Permalink
Merge pull request #21 from crow-fox/refactor/useURLQueryParams
Browse files Browse the repository at this point in the history
useCallbackで各関数をラップ
  • Loading branch information
crow-fox authored Apr 27, 2024
2 parents 966eb21 + 84d11fa commit 7e72612
Showing 1 changed file with 32 additions and 20 deletions.
52 changes: 32 additions & 20 deletions app/_utils/useURLQueryParams.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getObjectKeys } from "@/app/_utils/object";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCallback } from "react";

type Queries<T extends string> = Record<T, string | undefined>;

Expand All @@ -26,29 +27,40 @@ export function useURLQueryParams<T extends string>() {
const router = useRouter();
const pathname = usePathname();

function getQueryValue(querykey: T) {
return searchParams.get(querykey);
}
const getQueryValue = useCallback(
(querykey: T) => {
return searchParams.get(querykey);
},
[searchParams],
);

function updateQueries(queries: Queries<T>) {
const queryString = createQueryString(searchParams, queries);
router.push(`${pathname}?${queryString}`);
}
const updateQueries = useCallback(
(queries: Queries<T>) => {
const queryString = createQueryString(searchParams, queries);
router.push(`${pathname}?${queryString}`);
},
[pathname, router, searchParams],
);

function createHrefWithQueries(queries: Queries<T>) {
// <Link> の href に渡すための URL を生成
const queryString = createQueryString(searchParams, queries);
return `${pathname}?${queryString}`;
}
const createHrefWithQueries = useCallback(
(queries: Queries<T>) => {
const queryString = createQueryString(searchParams, queries);
return `${pathname}?${queryString}`;
},
[pathname, searchParams],
);

function deleteQueries(queryKeys: T[]) {
// 対象のクエリパラメーターのみ削除
const params = new URLSearchParams(searchParams);
for (const key of queryKeys) {
params.delete(key);
}
router.push(`${pathname}?${params.toString()}`);
}
const deleteQueries = useCallback(
(queryKeys: T[]) => {
// 対象のクエリパラメーターのみ削除
const params = new URLSearchParams(searchParams);
for (const key of queryKeys) {
params.delete(key);
}
router.push(`${pathname}?${params.toString()}`);
},
[pathname, router, searchParams],
);

return {
getQueryValue,
Expand Down

0 comments on commit 7e72612

Please sign in to comment.