Last active
October 27, 2024 17:43
-
-
Save merthanmerter/a9a56c9d5dbf18ac3b27ced21b97f020 to your computer and use it in GitHub Desktop.
Next.js use-params-with-type-conversion hook
This file contains hidden or 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
| export const useParamsWithTypeConversion = < | |
| T extends { [key: string]: (v: string | string[]) => number | boolean | string } | |
| >( | |
| conversions: T | |
| ) => { | |
| const params = useParams() | |
| const convertedParams = {} as { [K in keyof T]: ReturnType<T[K]> } | |
| for (const [key, conversion] of Object.entries(conversions)) { | |
| const paramValue = params[key as keyof typeof params] | |
| convertedParams[key as keyof T] = conversion(paramValue) as ReturnType<T[typeof key]> | |
| } | |
| return convertedParams | |
| } | |
| export default useParamsWithTypeConversion |
This file contains hidden or 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 { useParams } from "@tanstack/react-router"; | |
| export const useParamsWithTypeConversion = < | |
| T extends Record<string, (v: string) => number | boolean | string>, | |
| >( | |
| conversions: T, | |
| ) => { | |
| const params = useParams({ strict: false }); | |
| return Object.entries(conversions).reduce( | |
| (convertedParams, [key, conversion]) => { | |
| const paramValue = params?.[key as keyof typeof params]; | |
| if (paramValue) { | |
| convertedParams[key as keyof T] = conversion(paramValue) as ReturnType< | |
| T[typeof key] | |
| >; | |
| } | |
| return convertedParams; | |
| }, | |
| {} as { [K in keyof T]: ReturnType<T[K]> }, | |
| ); | |
| }; | |
| export default useParamsWithTypeConversion; |
This file contains hidden or 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
| const { | |
| id, // type: number | |
| foo, // type: boolean | |
| } = useParamsWithTypeConversion({ | |
| id: (val) => +val, | |
| foo: (val) => (val === 'true' ? true : false), | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment