Last active
July 17, 2023 12:58
-
-
Save yarabramasta/aafe1faf29d81967156d282b11918e63 to your computer and use it in GitHub Desktop.
Type-safe wrapper for Next.js useSearchParams hook
This file contains 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
// 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