Calling `FieldApi.handleChange(undefined)` sets field to field's default value instead #1614
Describe the bug#
When calling field.handleChange(undefined) in a framework, it will revert the field's value back to the default value after 1 rerender. It is because the .update() method will overwrite undefined.
- Since it occurs in
FieldApi.update, this error does not happen in form-core, but in framework adapters. - Calling
field.handleChange(null)works as expected. - If the default value is also
undefined, the change is unnoticeable.
Your minimal, reproducible example#
https://stackblitz.com/edit/vitejs-vite-wbyrntnr?file=src%2FApp.tsx
Steps to reproduce#
- There are two checkboxes per type of form (AppForm, Form)
- Uncheck the first one to set the value to
undefined. It will revert to the default value instead ofundefined. - Uncheck the second one to set the value to
null. It properly sets the value tonull.
Expected behavior#
As a user, I expect to be able to use undefined as an override value regardless of what the default Value is. Use cases include:
- Libraries such as
react-day-pickerwhich useundefinedinstead ofnullas their state - Personal implementations that use
undefined, such as optional select menus.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
It's related to the library itself, so the browser or framework has no impact.
TanStack Form adapter#
None
TanStack Form version#
v1.14.1
TypeScript version#
v5.8.3
Additional context#
Unit tests for adapters are lackluster. Simply removing the 'faulty' block on its own will not do. Make sure you don't accidentally break something else.
+1, I need to do some gymnastics with
nullto workaround this issueI can relate Hey romulovalez! It would be great if you could share the details of your workaround so others can benefit as well. Some simplified example would be highly appreciated 🙏
@nshaikhinurov I think what they're referring to is to use
nullinstead ofundefined.It's only
undefinedthat has this issue,nullworks as expected. You can confirm it in the reproducible example of the issue.i've just been iterating through the form values and setting
nulltoundefinedin theonSubmitcallback to get around this for now but a way to support this without that hack would be great+1, null works while undefined dont
Related to #1289.
This behavior is confusing and ended up costing me over an hour of debugging and questioning my own code. Plus the workaround made the affected code significantly more complicated to understand.
Really frustrating to run into.
Good news - I spent some time investigating with #1729 and I believe I'll have an idea on how to fix this.
The cause of it is way more complicated than I thought it would be, but it's no longer a mystery.
LeCarbonator(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
+1, I need to do some gymnastics with
nullto workaround this issue