Skip to content

Instantly share code, notes, and snippets.

@yarabramasta
Last active July 17, 2023 12:58
Show Gist options
  • Save yarabramasta/aafe1faf29d81967156d282b11918e63 to your computer and use it in GitHub Desktop.
Save yarabramasta/aafe1faf29d81967156d282b11918e63 to your computer and use it in GitHub Desktop.
Type-safe wrapper for Next.js useSearchParams hook
// Code by: Yara Bramasta (yarabram111@gmail.com)
import { useSearchParams } from 'next/navigation';
import { type z } from 'zod';
/**
* **Wrapper around Next.js useSearchParams hook**
*
* This hook is used to safely parse query params from the URL with `zod`.
*
* If you want to use other types besides strings, you'll need to manually transform the hook's return value on the schema using `z.transform`.
*
* @param schema The zod schema to use to parse the query params. This should be an object schema.
*
* @returns The parsed query params, or `null` if the query params are invalid or empty.
*
* @example
* ```ts
* // URL: /?modal=auth
* const state = useQueryParams(
* z.object({ modal: z.string().transform(v => v === 'auth') })
* );
* ```
*
* `Code by: Yara Bramasta (yarabram111@gmail.com)`
*/
export function useQueryParams<T extends z.ZodType<any>>(schema: T) {
const searchParams = useSearchParams();
const parsed = schema.safeParse(Object.fromEntries(searchParams.entries()));
if (!parsed.success) {
return null;
}
return parsed.data as z.infer<T>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment