Skip to main content

FormApi

The FormApi class is the core class for managing form state, validation, and submission in TanStack Form. It provides methods to interact with form data, validate fields, and handle form submissions.

Constructor

new FormApi<TFormData>(options?: FormOptions<TFormData>)
Creates a new FormApi instance with the given form options.
options
FormOptions<TFormData>
Configuration options for the form. See FormOptions for details.
FormApi
FormApi<TFormData>
A new FormApi instance

Example

import { FormApi } from '@tanstack/form-core'

interface FormData {
  firstName: string
  lastName: string
  email: string
}

const form = new FormApi<FormData>({
  defaultValues: {
    firstName: '',
    lastName: '',
    email: '',
  },
  onSubmit: async ({ value }) => {
    console.log('Form submitted:', value)
  },
})

Properties

options

options: FormOptions<TFormData>
The current options for the form.

state

get state(): FormState<TFormData>
The current state of the form, including values, errors, validation status, and more.

formId

get formId(): string
A unique identifier for this form instance.

fieldInfo

fieldInfo: Record<DeepKeys<TFormData>, FieldInfo<TFormData>>
A record containing information about each field in the form.

Methods

mount()

Mounts the form and initializes its state. Returns a cleanup function.
mount(): () => void
cleanup
() => void
A function to call when unmounting the form

Example

const cleanup = form.mount()

// Later, when unmounting
cleanup()

update()

Updates the form options and form state.
update(options?: FormOptions<TFormData>): void
options
FormOptions<TFormData>
New options to apply to the form

Example

form.update({
  defaultValues: {
    firstName: 'John',
    lastName: 'Doe',
    email: '[email protected]',
  },
})

reset()

Resets the form state to the default values. If values are provided, the form will be reset to those values instead.
reset(values?: TFormData, opts?: { keepDefaultValues?: boolean }): void
values
TFormData
Optional values to reset the form to
opts.keepDefaultValues
boolean
default:false
If true, keeps the existing default values instead of updating them

Example

// Reset to default values
form.reset()

// Reset to specific values and update defaults
form.reset({
  firstName: 'Jane',
  lastName: 'Smith',
  email: '[email protected]',
})

// Reset to specific values but keep original defaults
form.reset(
  {
    firstName: 'Jane',
    lastName: 'Smith',
    email: '[email protected]',
  },
  { keepDefaultValues: true }
)

handleSubmit()

Handles form submission, performs validation, and calls the appropriate onSubmit or onSubmitInvalid callbacks.
handleSubmit(submitMeta?: TSubmitMeta): Promise<void>
submitMeta
TSubmitMeta
Optional metadata to pass to the submit handlers

Example

const handleFormSubmit = async (e: FormEvent) => {
  e.preventDefault()
  await form.handleSubmit()
}

getFieldValue()

Gets the value of a specific field.
getFieldValue<TField extends DeepKeys<TFormData>>(
  field: TField
): DeepValue<TFormData, TField>
field
string
required
The field name (supports dot notation for nested fields)
value
any
The current value of the field

Example

const firstName = form.getFieldValue('firstName')
const street = form.getFieldValue('address.street')

setFieldValue()

Sets the value of a specific field and optionally updates the touched state.
setFieldValue<TField extends DeepKeys<TFormData>>(
  field: TField,
  updater: Updater<DeepValue<TFormData, TField>>,
  opts?: UpdateMetaOptions
): void
field
string
required
The field name (supports dot notation for nested fields)
updater
Updater<T>
required
A value or function that returns the new value
opts.dontUpdateMeta
boolean
default:false
If true, does not update field metadata
opts.dontValidate
boolean
default:false
If true, does not trigger validation
opts.dontRunListeners
boolean
default:false
If true, does not run field listeners

Example

// Set a value directly
form.setFieldValue('firstName', 'John')

// Set a value using an updater function
form.setFieldValue('firstName', (prev) => prev.toUpperCase())

// Set a value without triggering validation
form.setFieldValue('firstName', 'John', { dontValidate: true })

getFieldMeta()

Gets the metadata of a specific field.
getFieldMeta<TField extends DeepKeys<TFormData>>(
  field: TField
): FieldMeta | undefined
field
string
required
The field name
meta
FieldMeta | undefined
The field metadata including errors, touched state, etc.

Example

const meta = form.getFieldMeta('firstName')
if (meta?.errors.length) {
  console.log('Field has errors:', meta.errors)
}

setFieldMeta()

Updates the metadata of a specific field.
setFieldMeta<TField extends DeepKeys<TFormData>>(
  field: TField,
  updater: Updater<FieldMetaBase>
): void
field
string
required
The field name
updater
Updater<FieldMetaBase>
required
A value or function that returns the new metadata

validateField()

Validates a specific field.
validateField<TField extends DeepKeys<TFormData>>(
  field: TField,
  cause: ValidationCause
): ValidationError[] | Promise<ValidationError[]>
field
string
required
The field name to validate
cause
'change' | 'blur' | 'submit' | 'mount'
required
The cause of the validation
errors
ValidationError[] | Promise<ValidationError[]>
Array of validation errors (if any)

Example

const errors = await form.validateField('email', 'change')
if (errors.length > 0) {
  console.log('Validation failed:', errors)
}

validateAllFields()

Validates all fields in the form.
validateAllFields(cause: ValidationCause): Promise<ValidationError[]>
cause
'change' | 'blur' | 'submit' | 'mount'
required
The cause of the validation
errors
Promise<ValidationError[]>
Array of all validation errors from all fields

Array Field Methods

The FormApi provides methods for working with array fields:

pushFieldValue()

Pushes a value to an array field.
pushFieldValue<TField extends DeepKeysOfType<TFormData, any[]>>(
  field: TField,
  value: TData[number],
  opts?: UpdateMetaOptions
): void

insertFieldValue()

Inserts a value at a specific index in an array field.
insertFieldValue<TField extends DeepKeysOfType<TFormData, any[]>>(
  field: TField,
  index: number,
  value: TData[number],
  opts?: UpdateMetaOptions
): Promise<void>

replaceFieldValue()

Replaces a value at a specific index in an array field.
replaceFieldValue<TField extends DeepKeysOfType<TFormData, any[]>>(
  field: TField,
  index: number,
  value: TData[number],
  opts?: UpdateMetaOptions
): Promise<void>

removeFieldValue()

Removes a value at a specific index from an array field.
removeFieldValue<TField extends DeepKeysOfType<TFormData, any[]>>(
  field: TField,
  index: number,
  opts?: UpdateMetaOptions
): Promise<void>

swapFieldValues()

Swaps two values in an array field.
swapFieldValues<TField extends DeepKeysOfType<TFormData, any[]>>(
  field: TField,
  index1: number,
  index2: number,
  opts?: UpdateMetaOptions
): void

moveFieldValues()

Moves a value from one index to another in an array field.
moveFieldValues<TField extends DeepKeysOfType<TFormData, any[]>>(
  field: TField,
  fromIndex: number,
  toIndex: number,
  opts?: UpdateMetaOptions
): void

clearFieldValues()

Clears all values from an array field.
clearFieldValues<TField extends DeepKeysOfType<TFormData, any[]>>(
  field: TField,
  opts?: UpdateMetaOptions
): void

Example: Working with Array Fields

interface FormData {
  todos: Array<{ text: string; completed: boolean }>
}

const form = new FormApi<FormData>({
  defaultValues: { todos: [] },
})

// Add a new todo
form.pushFieldValue('todos', { text: 'Buy milk', completed: false })

// Insert at specific position
form.insertFieldValue('todos', 0, { text: 'First todo', completed: false })

// Remove a todo
form.removeFieldValue('todos', 1)

// Swap todos
form.swapFieldValues('todos', 0, 1)

// Clear all todos
form.clearFieldValues('todos')

deleteField()

Deletes a field and all its subfields from the form.
deleteField<TField extends DeepKeys<TFormData>>(field: TField): void
field
string
required
The field name to delete

resetField()

Resets a field value and metadata to its default state.
resetField<TField extends DeepKeys<TFormData>>(field: TField): void
field
string
required
The field name to reset

setErrorMap()

Updates the form’s error map.
setErrorMap(errorMap: FormValidationErrorMap): void
errorMap
FormValidationErrorMap
required
The new error map to set

getAllErrors()

Returns all form and field level errors.
getAllErrors(): {
  form: { errors: ValidationError[]; errorMap: ValidationErrorMap }
  fields: Record<string, { errors: ValidationError[]; errorMap: ValidationErrorMap }>
}
errors
object
An object containing all form and field errors

Example

const allErrors = form.getAllErrors()
console.log('Form errors:', allErrors.form.errors)
console.log('Field errors:', allErrors.fields)

Type Parameters

TFormData
any
required
The TypeScript type of the form data
TOnMount
FormValidateOrFn
Type of the onMount validator
TOnChange
FormValidateOrFn
Type of the onChange validator
TOnChangeAsync
FormAsyncValidateOrFn
Type of the onChangeAsync validator
TOnBlur
FormValidateOrFn
Type of the onBlur validator
TOnBlurAsync
FormAsyncValidateOrFn
Type of the onBlurAsync validator
TOnSubmit
FormValidateOrFn
Type of the onSubmit validator
TOnSubmitAsync
FormAsyncValidateOrFn
Type of the onSubmitAsync validator
TSubmitMeta
any
default:"never"
Type of the submission metadata

See Also

Build docs developers (and LLMs) love