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.
Configuration options for the form. See FormOptions for details.
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.
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.
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
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
Optional values to reset the form to
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>
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>
The field name (supports dot notation for nested fields)
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
The field name (supports dot notation for nested fields)
A value or function that returns the new value
If true, does not update field metadata
If true, does not trigger validation
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 })
Gets the metadata of a specific field.
getFieldMeta<TField extends DeepKeys<TFormData>>(
field: TField
): 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)
}
Updates the metadata of a specific field.
setFieldMeta<TField extends DeepKeys<TFormData>>(
field: TField,
updater: Updater<FieldMetaBase>
): void
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[]>
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
resetField()
Resets a field value and metadata to its default state.
resetField<TField extends DeepKeys<TFormData>>(field: TField): void
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 }>
}
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
The TypeScript type of the form data
Type of the onMount validator
Type of the onChange validator
Type of the onChangeAsync validator
Type of the onBlur validator
Type of the onBlurAsync validator
Type of the onSubmit validator
Type of the onSubmitAsync validator
Type of the submission metadata
See Also