Skip to content

Example Request: Custom form hook that takes generic schema #423

Answered by edmundhung
dan-gamble asked this question in Q&A
Discussion options

You must be logged in to vote
import { useForm } from '@conform-to/react';
import { parseWithZod, getZodConstraint } from '@conform-to/zod';
import { type ZodTypeAny, type input, type output } from 'zod';

function useLocalForm<Schema extends ZodTypeAny>({
    id,
    schema,
}: {
    id: string;
    schema: Schema;
}) {
    const [form, fields] = useForm<input<Schema>, output<Schema>, string[]>({
      id,
      constraint: getZodConstraint(schema),
      onValidate ({ formData }) {
        return parseWithZod(formData, { schema })
      },
      shouldValidate: 'onBlur',
      shouldRevalidate: 'onInput',
      onSubmit (e) {
        e.preventDefault()
      },
    })
  
    return { form, fields }
}

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@dan-gamble
Comment options

Answer selected by dan-gamble
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants