Skip to content

Instantly share code, notes, and snippets.

@merthanmerter
Last active October 27, 2024 17:43
Show Gist options
  • Select an option

  • Save merthanmerter/a9a56c9d5dbf18ac3b27ced21b97f020 to your computer and use it in GitHub Desktop.

Select an option

Save merthanmerter/a9a56c9d5dbf18ac3b27ced21b97f020 to your computer and use it in GitHub Desktop.
Next.js use-params-with-type-conversion hook
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
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;
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