Last active
June 25, 2023 02:05
-
-
Save ynifamily3/39d060a38dddf4351ded30a11fc68587 to your computer and use it in GitHub Desktop.
react-router-dom 헬퍼
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
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