T
TanStack2mo ago
frozen-sapphire

How to set default values asynchronously when using withForm?

I have a pretty big form that is split into smaller chunks by using "withForm", but now I'd like to set default values asynchronously. Is it even possible?
4 Replies
exotic-emerald
exotic-emerald2mo ago
well, withForm is a component accepting a form instance, so it has nothing to do with managing the defaultValues. The form hook is responsible for that
frozen-sapphire
frozen-sapphireOP2w ago
If I don't provide formOptions to withForm instance, then I lose typesafety. Is there a way to asynchronously set deafult values in formOptions?
exotic-emerald
exotic-emerald2w ago
no, but assuming that you guarantee it being set in the useAppForm hook ( and knowing the shape of defaultValues), you can either make an empty object representing it or a type assertion neither the object keys nor the object values are used by withForm at runtime, so it doesn't technically need them
const defaultValues: YourFormValues = { a: '' }
const sharedOpts = formOptions({
defaultValues,
validators: { /* ... */ }
})

const YourFormSection = withForm({
...sharedOpts,
render: () => {}
})

function YourComponent() {
const queryData: YourFormValues = useQuery() // some async data

const form = useAppForm({
...sharedOpts,
defaultValues: queryData ?? { a: '' }
})
}
const defaultValues: YourFormValues = { a: '' }
const sharedOpts = formOptions({
defaultValues,
validators: { /* ... */ }
})

const YourFormSection = withForm({
...sharedOpts,
render: () => {}
})

function YourComponent() {
const queryData: YourFormValues = useQuery() // some async data

const form = useAppForm({
...sharedOpts,
defaultValues: queryData ?? { a: '' }
})
}
frozen-sapphire
frozen-sapphireOP2w ago
you're right. I was confused because changes in fields are seen in "onChange" listener in the useAppForm(), but are not seen in the onSubmit / onSubmitInvalid I thought it has something to do with the default values

Did you find this page helpful?