Forked from AlemTuzlak/gist:89ee03a57c97cb820d6c30d7cd88b341
Created
August 10, 2023 14:45
-
-
Save juanpprieto/a9bf007124973b3c5ab19b21352ec249 to your computer and use it in GitHub Desktop.
Type inference with zod and remix-hook-form
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
import type { ZodType, z } from "zod"; | |
import { zodResolver } from "@hookform/resolvers/zod"; | |
import { getValidatedFormData as getValidatedFormDataPrimitive, useRemixForm as useForm, UseRemixFormOptions } from "remix-hook-form"; | |
interface UseRemixFormZodOptions<T extends ZodType, U extends FromZodType<T>> extends UseRemixFormOptions<U> { | |
schema: T; | |
} | |
export type FromZodType<T extends ZodType> = z.infer<T>; | |
export const useRemixForm = <T extends ZodType, U extends FromZodType<T>>(options: UseRemixFormZodOptions<T, U>) => { | |
return useForm<U>({ ...options, resolver: zodResolver(options.schema) }); | |
}; | |
export const getValidatedFormData = async <T extends z.ZodSchema>(request: Request, schema: T) => { | |
const result = await getValidatedFormDataPrimitive<z.infer<typeof schema>>( | |
request, | |
zodResolver(schema) | |
); | |
return result | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment