Skip to content

Instantly share code, notes, and snippets.

@AlemTuzlak
Created August 10, 2023 09:31
Show Gist options
  • Save AlemTuzlak/89ee03a57c97cb820d6c30d7cd88b341 to your computer and use it in GitHub Desktop.
Save AlemTuzlak/89ee03a57c97cb820d6c30d7cd88b341 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