T
TanStack4mo ago
fair-rose

Form composition with async values

I’ve read that the optionsForm need to be the same between composants. I create my default value inside a composant that receive data from props. How can i handle async default values?
4 Replies
fair-rose
fair-roseOP4mo ago
I want to declare a form in my MainForm components (with async default values), that have 4 sub forms (with a read mode and edit mode per sub form) I can’t find a way to declare a main form and re-use this form object into my subforms. Ideally, i dont want to use 4 useForm in each of my subform. I dont know if it’s clear
stormy-gold
stormy-gold4mo ago
type them the defaultValues will come from your original useAppForm, but you can inform withForm about the structure of the default values using the formOptions function So you'll want
type FormValues = {
// ...
}

const emptyForm: FormValues = {
// ...
}

const formOpts = formOptions({
defaultValues: emptyForm,
// ...
})

// your components
const Subform = withForm({
...formOpts,
// ...
})

function MainComponent() {
const form = useAppForm({
...formOpts,
defaultValues: asyncData ?? emptyForm
})
}
type FormValues = {
// ...
}

const emptyForm: FormValues = {
// ...
}

const formOpts = formOptions({
defaultValues: emptyForm,
// ...
})

// your components
const Subform = withForm({
...formOpts,
// ...
})

function MainComponent() {
const form = useAppForm({
...formOpts,
defaultValues: asyncData ?? emptyForm
})
}
fair-rose
fair-roseOP4mo ago
Thanks for your help, can i pass props to my subForm ?
stormy-gold
stormy-gold4mo ago
yes, withForm has a props property that allows you to define extra parameters from the Form Composition docs:
const ChildForm = withForm({
// ...

// Optional, but adds props to the `render` function in addition to `form`
props: {
// These props are also set as default values for the `render` function
// and won't be used at runtime
title: 'Child Form',
},
render: function Render({ form, title }) {
return (
<div>
<p>{title}</p>
<form.AppField
name="firstName"
children={(field) => <field.TextField label="First Name" />}
/>
<form.AppForm>
<form.SubscribeButton label="Submit" />
</form.AppForm>
</div>
)
},
})
const ChildForm = withForm({
// ...

// Optional, but adds props to the `render` function in addition to `form`
props: {
// These props are also set as default values for the `render` function
// and won't be used at runtime
title: 'Child Form',
},
render: function Render({ form, title }) {
return (
<div>
<p>{title}</p>
<form.AppField
name="firstName"
children={(field) => <field.TextField label="First Name" />}
/>
<form.AppForm>
<form.SubscribeButton label="Submit" />
</form.AppForm>
</div>
)
},
})

Did you find this page helpful?