-
-
Notifications
You must be signed in to change notification settings - Fork 543
Description
RFC (form-core): Handling Array Methods Called on null or undefined
Background
TanStack Form provides several helper methods for working with array fields.
In version form-core@1.24.4, these include:
moveFieldValuespushFieldValueswapFieldValuesclearFieldValuesinsertFieldValueremoveFieldValuereplaceFieldValue
Currently, these methods can only be used if the field type explicitly extends unknown[]. However, there have been requests (#1588 ) to support optional arrays.
The Problem
TypeScript allows us to express such optional arrays easily, but at runtime the behavior is inconsistent.
Consider this example:
const form = useForm({
defaultValues: {
people: null as null | string[]
}
})
form.pushFieldValue('people', 'New person')In the current version:
- Some methods error,
- Some methods don't do anything,
- Some methods silently create a new array
There are no runtime checks ensuring consistent behavior when array methods are called on null or undefined
Goal
We want consistent, predictable behavior across all array helper methods when the field value is null or undefined.
This RFC plans to define that behaviour and make it guarantee the runtime behaviour.
Once a decision is made, all array methods (swapFieldValues, removeFieldValue etc.) will follow this rule and be tested for it.
Your Feedback
If you currently use arrays in your forms, please share your expectations for how the following code should behave:
form.pushFieldValue('people', 'New person')Here are some of our proposed options. If you have other suggestions or proposals, feel free to share!
- Throw an error: The operation should explicitly fail if it encountered
nullorundefined. - Create an empty array: The operation should first initialize an array, and then apply the changes if possible.
pushFieldValue('people', 'New Person')transformsnull -> ['New Person']swapFieldValues('people', 1, 2)transformsnull -> []
- Do nothing: The operation should not apply any changes if the field is not an array.
Frequently Asked Questions
Will this be a breaking change?
Possibly. The current type definitions don't allow you to call these methods on optional arrays. If a field called the array method, it was an inconsistent mix of doing nothing, throwing an error or creating an array.
With the plans to provide optional array support, we want to enforce consistent behaviour.