Skip to content

[RFC] form-core: Handling Array Methods Called on null or undefined #1823

@LeCarbonator

Description

@LeCarbonator

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:

  • moveFieldValues
  • pushFieldValue
  • swapFieldValues
  • clearFieldValues
  • insertFieldValue
  • removeFieldValue
  • replaceFieldValue

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!

  1. Throw an error: The operation should explicitly fail if it encountered null or undefined.
  2. Create an empty array: The operation should first initialize an array, and then apply the changes if possible.
    • pushFieldValue('people', 'New Person') transforms null -> ['New Person']
    • swapFieldValues('people', 1, 2) transforms null -> []
  3. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions