T
TanStack16mo ago
itchy-amethyst

Pass a zod schema to a form to ensure all required values are captured?

So IIRC with react-hook-form you can pass a zod schema to a useForm and it will give you typesense if you forgot to set a defaultField or a formField. Is there a similar pattern here? for now im just casting the type
export function AddFieldSheet() {
const [open, setOpen] = React.useState(false)
// const [value, setValue] = React.useState('')
const [showDescription, setShowDescription] = React.useState(false)

const { mutate, data, error, isError } = mutationQueries.useCreateField()

const form = useForm({
defaultValues: {
fieldName: '',
fieldType: [],
fieldDescription: '',
},
validatorAdapter: zodValidator,
onSubmit: async ({ value }) => {
console.log(value)
mutate(value as unknown as InsertFields)
if (isError) {
console.error(`Error creating field: ${error}`)
}
},
})

return (
<DrawerSheet open={open} onOpenChange={setOpen}>
<DrawerSheetTrigger asChild>
...
<form
onSubmit={(e) => {
e.preventDefault()
e.stopPropagation()
form.handleSubmit()
}}
className="flex flex-col gap-4"
>
<form.Field name="fieldName" validators={{ onChange: insertFieldsSchema.shape.name }}>
{(field) => (
<div>
<Label>Field Name</Label>
<Input
id="fieldName"
type="text"
value={field.state.value}
onChange={(e) => field.handleChange(e.target.value)}
/>
</div>
)}
</form.Field>
export function AddFieldSheet() {
const [open, setOpen] = React.useState(false)
// const [value, setValue] = React.useState('')
const [showDescription, setShowDescription] = React.useState(false)

const { mutate, data, error, isError } = mutationQueries.useCreateField()

const form = useForm({
defaultValues: {
fieldName: '',
fieldType: [],
fieldDescription: '',
},
validatorAdapter: zodValidator,
onSubmit: async ({ value }) => {
console.log(value)
mutate(value as unknown as InsertFields)
if (isError) {
console.error(`Error creating field: ${error}`)
}
},
})

return (
<DrawerSheet open={open} onOpenChange={setOpen}>
<DrawerSheetTrigger asChild>
...
<form
onSubmit={(e) => {
e.preventDefault()
e.stopPropagation()
form.handleSubmit()
}}
className="flex flex-col gap-4"
>
<form.Field name="fieldName" validators={{ onChange: insertFieldsSchema.shape.name }}>
{(field) => (
<div>
<Label>Field Name</Label>
<Input
id="fieldName"
type="text"
value={field.state.value}
onChange={(e) => field.handleChange(e.target.value)}
/>
</div>
)}
</form.Field>
3 Replies
itchy-amethyst
itchy-amethystOP16mo ago
@crutchcorn any chance you could take a look?
quickest-silver
quickest-silver16mo ago
Don't tag maintainers But also yes you just pass the type of the shape as the first argument of useForm
itchy-amethyst
itchy-amethystOP16mo ago
sorry, noted. thanks!

Did you find this page helpful?