Skip to content

Instantly share code, notes, and snippets.

@ynifamily3
Last active June 25, 2023 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ynifamily3/39d060a38dddf4351ded30a11fc68587 to your computer and use it in GitHub Desktop.
Save ynifamily3/39d060a38dddf4351ded30a11fc68587 to your computer and use it in GitHub Desktop.
react-router-dom 헬퍼
import { useCallback, useMemo } from "react";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
const _getAll = (urlSearchParams: URLSearchParams) => {
const ret: Record<string, string[]> = {};
for (const [k, v] of urlSearchParams.entries()) {
if (ret[k]) {
ret[k].push(v);
} else {
ret[k] = [v];
}
}
return ret;
};
type ToQueryHashParams = {
query?: Record<string, string | string[]>;
hash?: Record<string, string | string[]>;
};
type GoOptions = {
reset?: boolean;
replace?: boolean;
pathname?: string;
};
type GetHrefOptions = {
reset?: boolean;
pathname?: string;
};
export function useRouteHelper() {
const navigate = useNavigate();
const { hash } = useLocation();
const hashParams = useMemo(() => new URLSearchParams(hash.slice(1)), [hash]);
const [searchParams] = useSearchParams();
const hAll = useMemo(() => _getAll(hashParams), [hashParams]);
const hget = useCallback((key: string) => hAll[key], [hAll]);
const qAll = useMemo(() => _getAll(searchParams), [searchParams]);
const qget = useCallback((key: string) => qAll[key], [qAll]);
const getHref = useCallback(
(toQueryHashParams: ToQueryHashParams, options?: GetHrefOptions) => {
//
},
[]
);
const go = useCallback(
(toQueryHashParams: ToQueryHashParams, options?: GoOptions) => {
//
navigate(``, { replace: options?.replace });
},
[navigate]
);
return {
hAll,
hget,
qAll,
qget,
getHref,
go,
/**
* @deprecated 대신 `hAll`로 직접 값을 가져올 수 있습니다.
*/
hgetAll: useCallback(() => hAll, [hAll]),
/**
* @deprecated 대신 `qAll`로 직접 값을 가져올 수 있습니다.
*/
qgetAll: useCallback(() => qAll, [qAll]),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment