T
TanStack3mo ago
foreign-sapphire

Remove value from the form on field unmount

I have 2 fields: name and description. The description is optional, and there is logic that hides the description field. By saying "hides," I mean this:
const [showDescription, setShowDescription] = useState(true);

...

{showDescription && <form.Field name="description" ... />}
const [showDescription, setShowDescription] = useState(true);

...

{showDescription && <form.Field name="description" ... />}
The scenario: - Input a name - Input a description - Hide the description field - Submit the form - In onSubmit callback I receive both name and description, but expect to receive only name Is there a way to implement this?
2 Replies
manual-lavender
manual-lavender3mo ago
If the value is an external state, either with a useEffect
useEffect(() => {
if (!showDescription) {
form.setFieldValue('description', '')
}
}, [showDescription, form])
useEffect(() => {
if (!showDescription) {
form.setFieldValue('description', '')
}
}, [showDescription, form])
or by checking in onSubmit
const form = useForm({
// ...
onSubmit: async ({ value }) => {
if (!showDescription) {
await callServer({ name: value.name })
} else {
// name, description
await callServer(value)
}
}
})
const form = useForm({
// ...
onSubmit: async ({ value }) => {
if (!showDescription) {
await callServer({ name: value.name })
} else {
// name, description
await callServer(value)
}
}
})
If the value is internal in the form state, with a listener:
<form.Field
name="showDescription"
listeners={{
onChange: ({ value, fieldApi }) => {
if (!value) {
fieldApi.form.setFieldValue('description', '')
}
}
}}
<form.Field
name="showDescription"
listeners={{
onChange: ({ value, fieldApi }) => {
if (!value) {
fieldApi.form.setFieldValue('description', '')
}
}
}}
@AlexG
foreign-sapphire
foreign-sapphireOP3mo ago
Awesome! Thanks @Luca | LeCarbonator , the last one is exactly what I was looking for @Luca | LeCarbonator, it turned out what I'm really looking for is this:
<form.Field
name="description"
listeners={{
onUnmount: () => form.deleteField('description')
}}
<form.Field
name="description"
listeners={{
onUnmount: () => form.deleteField('description')
}}
I made a feature request https://github.com/TanStack/form/discussions/1576

Did you find this page helpful?