Skip to content

Instantly share code, notes, and snippets.

@temoncher
Created July 28, 2022 09:43
Show Gist options
  • Save temoncher/18e112da012070511af6be80b33909f8 to your computer and use it in GitHub Desktop.
Save temoncher/18e112da012070511af6be80b33909f8 to your computer and use it in GitHub Desktop.
Search params typed with `zod` lib
import { useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';
import { z } from 'zod';
export const useTypedParams = <T extends z.SomeZodObject>(zodSchema: T) => {
type TParams = z.infer<T>;
const [urlSearchParams, setUrlSearchParams] = useSearchParams();
const searchParams = useMemo<TParams>(() => {
const parsedParams = Object.fromEntries(urlSearchParams);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return zodSchema.parse(parsedParams);
}, [zodSchema, urlSearchParams]);
const clearSearchParams = () => {
setUrlSearchParams({});
};
const setSearchParam = <K extends keyof TParams>(key: K, newValue: TParams[K]) => {
setUrlSearchParams({
...searchParams,
[key]: newValue,
});
};
const setSearchParams = (newParams: TParams) => {
setUrlSearchParams(newParams);
};
return {
searchParams,
setSearchParams,
setSearchParam,
clearSearchParams,
} as const;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment