Issue
I want to create a React hook for retrieving url search params and return a correctly typed object, calling it like this:
const { id, slug } = useTypedSearchParams<{ id: number; slug: string }>();
This would return id
typed as number
and slug
typed as string
.
I have tried various implementations with no success, the main problem being building an object from a type definition and conditionally calling parseInt
for number
fields.
Solution
You can use a library like Zod to handle this problem elegantly. This version throws an exception in case of validation errors.
import { z } from 'zod';
function useTypedSearchParams<T extends z.Schema>(schema: T): z.infer<T> {
const [searchParams] = useSearchParams();
return schema.parse(Object.fromEntries(searchParams));
}
function Home() {
const mySearchParamsSchema = z.object({
someText: z.coerce.string(),
someNumber: z.coerce.number(),
someBool: z.coerce.boolean().optional(),
});
try {
const searchParams = useTypedSearchParams(mySearchParamsSchema);
console.log('Search Params', searchParams);
} catch (e) {
console.log(e);
}
return <p></p>
}
The type of search params is infeerred as follows:
const searchParams: {
someText: string;
someNumber: number;
someBool?: boolean | undefined;
}
Answered By - Lesiak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.