Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juanpprieto/a9bf007124973b3c5ab19b21352ec249 to your computer and use it in GitHub Desktop.
Save juanpprieto/a9bf007124973b3c5ab19b21352ec249 to your computer and use it in GitHub Desktop.
Type inference with zod and remix-hook-form
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