T
TanStack5mo ago
genetic-orange

Form composition

Hello, how do you refactor the form and submissions? Currently i have page with form and useAppForm hook where i have onSubmit actions. something like this //page const form = useAppForm({ ...formOpts, onSubmit: async({value}) => { const response= await submit(value) if(response){ //other stuff setResult(response) toast("success")} } }) And i have config formOpts file with types, zod and validation with another onSubmit const formSchema = z.object({ ... }) export const formOpts = formOptions({ defaultValues: { ... }, validators: { onSubmit: formSchema, }, }) And form component which is just form and fields What is the best way people do forms in tanstack? I think about moving form validation from the page to custom hook that will return form, submit and result values
1 Reply
exotic-emerald
exotic-emerald5mo ago
I'm not sure where the issue is. The code above looks pretty solid. Do you have concerns with the current setup? if you mean reducing nesting, withForm allows you to spread the form across multiple files. It accepts the same form options If we have a complex form structure, this is usually how we do it:
form-group/
├─ Logic.ts
│ converts Dto to form values
│ converts form values to Dto
│ generates and exports formOpts

├─ MainForm.tsx
| groups form sections
| manages backend calls
| contains the form hook
├─ FormSection1.tsx
├─ FormSection2.tsx
form-group/
├─ Logic.ts
│ converts Dto to form values
│ converts form values to Dto
│ generates and exports formOpts

├─ MainForm.tsx
| groups form sections
| manages backend calls
| contains the form hook
├─ FormSection1.tsx
├─ FormSection2.tsx

Did you find this page helpful?