### Development Setup Commands Source: https://tanstack.com/form/latest/docs/framework/react/examples/tanstack-start These commands are used to install dependencies and start the development server for the project. Run these in your terminal. ```sh pnpm install pnpm dev ``` -------------------------------- ### Project Dependencies for UI Libraries Example Source: https://tanstack.com/form/latest/docs/framework/react/examples/ui-libraries This package.json file lists the dependencies required for the React UI Libraries example, including Material UI, Mantine, TanStack Form, and development tools like Vite and TypeScript. ```json { "name": "@tanstack/form-example-react-ui-libraries", "private": true, "type": "module", "scripts": { "dev": "vite --port=3001", "build": "vite build", "preview": "vite preview", "test:types": "tsc --noEmit" }, "dependencies": { "@emotion/react": "11.14.0", "@emotion/styled": "11.14.1", "@mantine/core": "7.17.8", "@mantine/hooks": "7.17.8", "@mui/material": "6.5.0", "@tanstack/react-form": "^1.33.0", "@yme/lay-postcss": "0.1.0", "postcss": "8.5.6", "postcss-preset-mantine": "1.18.0", "postcss-simple-vars": "7.0.1", "react": "19.1.0", "react-dom": "19.1.0" }, "devDependencies": { "@tanstack/react-devtools": "^0.9.7", "@tanstack/react-form-devtools": "^0.2.29", "@types/react": "~19.1.0", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^5.1.1", "@vitejs/plugin-react-swc": "^3.11.0", "typescript": "5.9.3", "vite": "^7.2.2" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ``` -------------------------------- ### TanStack Start: Get Form Data from Server Source: https://tanstack.com/form/latest/docs/framework/react/guides/ssr.md Creates a server function in TanStack Start to retrieve form data. This is typically used in a loader to fetch the server's form state and pass it to the client. ```typescript import { getFormData } from '@tanstack/react-form-start' export const getFormDataFromServer = createServerFn({ method: 'GET', }).handler( async () => { return getFormData() }, ) ``` -------------------------------- ### Install TanStack Devtools and Form Plugin Source: https://tanstack.com/form/latest/docs/framework/react/guides/devtools.md Installs the necessary TanStack Devtools and the specific plugin for TanStack Form using npm. These are essential for enabling the devtools functionality. ```bash npm i @tanstack/react-devtools npm i @tanstack/react-form-devtools ``` -------------------------------- ### React App Setup with Material UI and TanStack Devtools Source: https://tanstack.com/form/latest/docs/framework/react/examples/ui-libraries This snippet sets up a React application using Material UI for theming and styling. It also integrates TanStack Form Devtools for easier form debugging. Ensure you have the necessary Material UI and TanStack Form Devtools packages installed. ```tsx import React from 'react' import { TanStackDevtools } from '@tanstack/react-devtools' import { formDevtoolsPlugin } from '@tanstack/react-form-devtools' import { createRoot } from 'react-dom/client' import { createTheme } from '@mui/material/styles' import { red } from '@mui/material/colors' import { ThemeProvider } from '@emotion/react' import { CssBaseline } from '@mui/material' import MainComponent from './MainComponent' const theme = createTheme({ palette: { primary: { main: '#556cd6', }, secondary: { main: '#19857b', }, error: { main: red.A400, }, }, }) export default function App() { return ( ) } const rootElement = document.getElementById('root')! createRoot(rootElement).render( , ) ``` -------------------------------- ### Complete Array Form Implementation Source: https://tanstack.com/form/latest/docs/framework/react/guides/arrays.md A comprehensive example showing a full form with array management, submission handling, and subscription for button state updates. ```jsx function App() { const form = useForm({ defaultValues: { people: [] }, onSubmit({ value }) { alert(JSON.stringify(value)) }, }) return (
{ e.preventDefault(); e.stopPropagation(); form.handleSubmit() }}> {(field) => (
{field.state.value.map((_, i) => ( {(subField) => ( subField.handleChange(e.target.value)} /> )} ))}
)}
[state.canSubmit, state.isSubmitting]}> {([canSubmit, isSubmitting]) => }
) } ``` -------------------------------- ### Setup React Project with UI Libraries Source: https://tanstack.com/form/latest/docs/framework/react/examples/ui-libraries Initializes a React application with necessary imports for TanStack Form, Material UI, and devtools. Sets up a basic Material UI theme. ```typescript import React from 'react' import { TanStackDevtools } from '@tanstack/react-devtools' import { formDevtoolsPlugin } from '@tanstack/react-form-devtools' import { createRoot } from 'react-dom/client' import { createTheme } from '@mui/material/styles' import { red } from '@mui/material/colors' import { ThemeProvider } from '@emotion/react' import { CssBaseline } from '@mui/material' import MainComponent from './MainComponent' const theme = createTheme({ palette: { primary: { main: '#556cd6', }, secondary: { main: red[500], }, }, }) const rootElement = document.getElementById('root') if (!rootElement) { throw new Error('Failed to find the root element') } const root = createRoot(rootElement) root.render( {/* */} ) ``` -------------------------------- ### TanStack Start: Define Form Options Source: https://tanstack.com/form/latest/docs/framework/react/guides/ssr.md Defines the initial shape and default values for a TanStack Form within a TanStack Start application. This configuration is shared between client and server. ```typescript import { formOptions } from '@tanstack/react-form-start' // You can pass other form options here export const formOpts = formOptions({ defaultValues: { firstName: '', age: 0, }, }) ``` -------------------------------- ### TanStack Start: Client-Side Form Component Source: https://tanstack.com/form/latest/docs/framework/react/guides/ssr.md A React component for TanStack Start that integrates TanStack Form. It uses `useForm`, `useStore`, and `useTransform` to manage form state, handle submissions via `handleForm`, and load initial data using `getFormDataFromServer`. ```tsx import { createFileRoute } from '@tanstack/react-router' import { mergeForm, useForm, useStore, useTransform, } from '@tanstack/react-form-start' export const Route = createFileRoute('/')({ component: Home, loader: async () => ({ state: await getFormDataFromServer(), }), }) function Home() { const { state } = Route.useLoaderData() const form = useForm({ ...formOpts, transform: useTransform((baseForm) => mergeForm(baseForm, state), [state]), }) const formErrors = useStore(form.store, (formState) => formState.errors) return (
{formErrors.map((error) => (

{error}

))} value < 8 ? 'Client validation: You must be at least 8' : undefined, }} > {(field) => { return (
field.handleChange(e.target.valueAsNumber)} /> {field.state.meta.errors.map((error) => (

{error}

))}
) }}
[formState.canSubmit, formState.isSubmitting]} > {([canSubmit, isSubmitting]) => ( )}
) } ``` -------------------------------- ### TanStack Start: Server-Side Form Validation Source: https://tanstack.com/form/latest/docs/framework/react/guides/ssr.md Implements server-side validation for form submissions in TanStack Start. It uses `createServerValidate` to define validation logic and `createServerFn` to handle the POST request, including error handling for validation failures. ```typescript import { createServerValidate, ServerValidateError, } from '@tanstack/react-form-start' const serverValidate = createServerValidate({ ...formOpts, onServerValidate: ({ value }) => { if (value.age < 12) { return 'Server validation: You must be at least 12 to sign up' } }, }) export const handleForm = createServerFn({ method: 'POST', }) .inputValidator((data: unknown) => { if (!(data instanceof FormData)) { throw new Error('Invalid form data') } return data }) .handler(async (ctx) => { try { const validatedData = await serverValidate(ctx.data) console.log('validatedData', validatedData) // Persist the form data to the database // await sql` // INSERT INTO users (name, email, password) // VALUES (${validatedData.name}, ${validatedData.email}, ${validatedData.password}) // ` } catch (e) { if (e instanceof ServerValidateError) { // Log form errors or do any other logic here return e.response } // Some other error occurred when parsing the form console.error(e) setResponseStatus(500) return 'There was an internal error' } return 'Form has validated successfully' }) ``` -------------------------------- ### Using `useAppForm` and `useTypedAppFormContext` Source: https://tanstack.com/form/latest/docs/framework/react/guides/form-composition.md This example demonstrates how to set up a parent component with `useAppForm` and access the form instance in a child component using `useTypedAppFormContext`. This is a context-based fallback for form composition. ```tsx // sharedOpts.ts const formOpts = formOptions({ /* ... */ }) function ParentComponent() { const form = useAppForm({ ...formOptions /* ... */ }) return ( ) } function ChildComponent() { const form = useTypedAppFormContext({ ...formOptions }) // You now have access to form components, field components and fields } ``` -------------------------------- ### Basic TanStackDevtools Integration in React Source: https://tanstack.com/form/latest/docs/framework/react/guides/devtools.md Demonstrates the basic setup for integrating TanStackDevtools into a React application's root component. It shows how to import and render the component to enable basic devtools. ```tsx import { TanStackDevtools } from '@tanstack/react-devtools' import App from './App' createRoot(document.getElementById('root')!).render( , ) ``` -------------------------------- ### onMount Source: https://tanstack.com/form/latest/docs/reference/interfaces/FieldValidators.md An optional function that runs on the mount event of an input. It can be used for initial validation or setup. ```APIDOC ## onMount ### Description An optional function that runs when a field is mounted. This can be used for initial validation or setup tasks. ### Signature ```ts optional onMount: RejectPromiseValidator; ``` ``` -------------------------------- ### Implement Dynamic Validation with onDynamic Source: https://tanstack.com/form/latest/docs/framework/react/guides/dynamic-validation.md Demonstrates the basic setup of dynamic validation by providing an onDynamic function to the validators object and enabling it via revalidateLogic. ```tsx import { revalidateLogic, useForm } from '@tanstack/react-form' const form = useForm({ defaultValues: { firstName: '', lastName: '', }, validationLogic: revalidateLogic(), validators: { onDynamic: ({ value }) => { if (!value.firstName) { return { firstName: 'A first name is required' } } return undefined }, }, }) ``` -------------------------------- ### React Form Setup with Devtools Source: https://tanstack.com/form/latest/docs/framework/react/examples/simple Sets up a React component to use TanStack Form, including the necessary imports for React, TanStack Devtools, and Form Devtools. This is the foundational structure for creating forms. ```tsx import * as React from 'react' import { createRoot } from 'react-dom/client' import { TanStackDevtools } from '@tanstack/react-devtools' import { formDevtoolsPlugin } from '@tanstack/react-form-devtools' import { useForm } from '@tanstack/react-form' import type { AnyFieldApi } from '@tanstack/react-form' function FieldInfo({ field }: { field: AnyFieldApi }) { return ( <> {field.state.meta.isTouched && !field.state.meta.isValid ? ( {field.state.meta.errors.join(', ')} ) : null} ) } function App() { const form = useForm({ defaultValues: { firstName: '', lastName: '', }, onSubmit: async ({ value }) => { // Do something with data await new Promise((resolve) => setTimeout(resolve, 1000)) alert(`Form submitted with values: ${JSON.stringify(value, null, 2)}`) }, }) return (
{ e.preventDefault() e.stopPropagation() form.handleSubmit() }} > 'First name is required' }} children={({ input, meta }) => (
)} /> (
)} />
( )} />
) } const rootElement = document.getElementById('root') if (!rootElement) throw new Error('Failed to find the root element') const root = createRoot(rootElement) root.render() ``` -------------------------------- ### Implementing Dynamic Array Fields in TanStack Form Source: https://tanstack.com/form/latest/docs/framework/react/guides/arrays.md Demonstrates the basic setup for an array field using the mode='array' prop. It shows how to map over the array state to render fields and use pushValue to dynamically add new entries. ```jsx function App() { const form = useForm({ defaultValues: { people: [], }, }) return ( {(field) => (
{field.state.value.map((_, i) => { // ... })}
)}
) } ``` -------------------------------- ### TanStack Form with Lit Example Source: https://tanstack.com/form/latest/docs/overview.md This snippet shows a complete Lit component using TanStack Form. It includes form initialization, field definitions with validation, and rendering of form elements and error messages. Use this for a full-fledged form implementation in Lit. ```typescript import { LitElement, html, nothing } from 'lit' import { customElement } from 'lit/decorators.js' import { TanStackFormController } from '@tanstack/lit-form' import { repeat } from 'lit/directives/repeat.js' @customElement('tanstack-form-demo') export class TanStackFormDemo extends LitElement { #form = new TanStackFormController(this, { defaultValues: { firstName: '', lastName: '', }, onSubmit({ value }) { // Do something with form data console.log(value) }, }) render() { return html`
{ e.preventDefault() e.stopPropagation() this.#form.api.handleSubmit() }} > ${this.#form.field( { name: `firstName`, validators: { onChange: ({ value }) => !value ? 'A first name is required' : value.length < 3 ? 'First name must be at least 3 characters' : undefined, onChangeAsyncDebounceMs: 500, onChangeAsync: async ({ value }) => { await new Promise((resolve) => setTimeout(resolve, 1000)) return ( value.includes('error') && 'No "error" allowed in first name' ) }, }, }, (field) => { return html`
${field.state.meta.isTouched && !field.state.meta.isValid ? html`${repeat( field.state.meta.errors, (__, idx) => idx, (error) => { return html`
${error}
` }, )}` : nothing} ${field.state.meta.isValidating ? html`

Validating...

` : nothing}
` }, )}
${this.#form.field( { name: `lastName`, }, (field) => { return html`
` }, )}
` } } ``` -------------------------------- ### Get Field Info Method Source: https://tanstack.com/form/latest/docs/reference/classes/FormApi.md Retrieves detailed information about a specific field. This includes its configuration and state. It requires the field name as input. ```typescript getFieldInfo(field): FieldInfo; ``` -------------------------------- ### Rendering a Parent Component with a Nested Form Source: https://tanstack.com/form/latest/docs/framework/react/guides/form-composition.md This example illustrates how to render a parent component that utilizes a nested form. It shows the usage of `useAppForm` to create the main form instance and then passes it down to the `ChildForm` component. ```tsx // /src/features/people/page.ts const Parent = () => { const form = useAppForm({ ...formOpts, }) return } ``` -------------------------------- ### Correct Usage of Named Render Function with `withForm` Source: https://tanstack.com/form/latest/docs/framework/react/guides/form-composition.md This example shows the correct way to define the `render` prop with `withForm` using a named function, which resolves ESLint hook usage errors. ```tsx const ChildForm = withForm({ // ... render: function Render({ form, title }) { // ... }, }) ``` -------------------------------- ### Breaking Down Large Forms with `withForm` Source: https://tanstack.com/form/latest/docs/framework/react/guides/form-composition.md This example shows how to use the `withForm` higher-order component to break down a large form into smaller, manageable pieces. It defines a `ChildForm` component that can be rendered independently or as part of a larger form structure. ```tsx const { useAppForm, withForm } = createFormHook({ fieldComponents: { TextField, }, formComponents: { SubscribeButton, }, fieldContext, formContext, }) const ChildForm = withForm({ // These values are only used for type-checking, and are not used at runtime // This allows you to `...formOpts` from `formOptions` without needing to redeclare the options defaultValues: { firstName: 'John', lastName: 'Doe', }, // Optional, but adds props to the `render` function in addition to `form` props: { // These props are also set as default values for the `render` function title: 'Child Form', }, render: function Render({ form, title }) { return (

{title}

} />
) }, }) function App() { const form = useAppForm({ defaultValues: { firstName: 'John', lastName: 'Doe', }, }) return } ``` -------------------------------- ### Listening to Form Field Events with TanStack Form Source: https://tanstack.com/form/latest/docs/framework/react/guides/basic-concepts.md Demonstrates how to set up listeners for specific form field events in TanStack Form. The example shows how to trigger side effects, such as resetting another field, when a field's value changes. ```tsx { console.log(`Country changed to: ${value}, resetting province`) form.setFieldValue('province', '') }, }} /> ``` -------------------------------- ### Creating a Custom Text Field Component Source: https://tanstack.com/form/latest/docs/framework/react/guides/form-composition.md This example demonstrates how to create a custom text field component that utilizes `useFieldContext` to access and manage its state within the form. It's designed to be reusable and extendable. ```tsx // imported from the same AppForm you want to extend import { useFieldContext } from 'weyland-yutan-corp/forms-context' export function CustomTextField({ label }: { label: string }) { const field = useFieldContext() return (
) } ``` -------------------------------- ### Field-Level Listeners Source: https://tanstack.com/form/latest/docs/framework/react/guides/listeners.md Demonstrates how to use the `listeners` API on a form field to react to events like `onChange`. This example shows how changing the 'country' field resets the 'province' field. ```APIDOC ## Field-Level Listeners ### Description Attaches listeners to individual form fields to react to specific events. ### Method N/A (Configuration within `useForm`) ### Endpoint N/A ### Parameters #### Field Configuration - **listeners** (object) - Optional - An object containing event listener functions. - **onChange** (function) - Callback function executed when the field's value changes. - **onBlur** (function) - Callback function executed when the field loses focus. - **onMount** (function) - Callback function executed when the field is mounted. - **onUnmount** (function) - Callback function executed when the field is unmounted. ### Request Example ```tsx { console.log(`Country changed to: ${value}, resetting province`) form.setFieldValue('province', '') }, }} > {(field) => ( )} ``` ### Response N/A (Side effects are triggered) ### Error Handling N/A ``` -------------------------------- ### Integrate TanStack Form with Mantine Components Source: https://tanstack.com/form/latest/docs/framework/react/guides/ui-libraries.md This example demonstrates how to use the useForm hook and Field component to bind Mantine's TextInput and Checkbox components to TanStack Form state. ```tsx import { TextInput, Checkbox } from '@mantine/core' import { useForm } from '@tanstack/react-form' export default function App() { const { Field, handleSubmit, state } = useForm({ defaultValues: { name: '', isChecked: false, }, onSubmit: async ({ value }) => { console.log(value) }, }) return ( <>
{ e.preventDefault() handleSubmit() }} > ( handleChange(e.target.value)} onBlur={handleBlur} placeholder="Enter your name" /> )} /> ( handleChange(e.target.checked)} onBlur={handleBlur} checked={state.value} /> )} />
{JSON.stringify(state.values, null, 2)}
) } ``` -------------------------------- ### Basic Form Component with TanStack Form Source: https://tanstack.com/form/latest/docs/framework/react/examples/simple This component sets up a simple form with 'firstName' and 'lastName' fields. It includes basic validation and an onSubmit handler. Use this as a starting point for forms in your React application. ```tsx import * as React from 'react' import { createRoot } from 'react-dom/client' import { TanStackDevtools } from '@tanstack/react-devtools' import { formDevtoolsPlugin } from '@tanstack/react-form-devtools' import { useForm } from '@tanstack/react-form' import type { AnyFieldApi } from '@tanstack/react-form' function FieldInfo({ field }: { field: AnyFieldApi }) { return ( <> {field.state.meta.isTouched && !field.state.meta.isValid ? ( _{field.state.meta.errors.join(',')}_ ) : null} {field.state.meta.isValidating ? 'Validating...' : null} ) } export default function App() { const form = useForm({ defaultValues: { firstName: '', lastName: '', }, onSubmit: async ({ value }) => { // Do something with form data console.log(value) }, }) return ( <>
{ e.preventDefault() e.stopPropagation() form.handleSubmit() }} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }} > (!value ? 'First name is required' : undefined) }} children={({ state, change, blur }) => ( <> blur()} onChange={(e) => change(e.target.value)} /> )} /> (!value ? 'Last name is required' : undefined) }} children={({ state, change, blur }) => ( <> blur()} onChange={(e) => change(e.target.value)} /> )} /> canSubmit} children={({ canSubmit }) => ( )} />
{JSON.stringify(form.state.values, null, 2)}
) } const rootElement = document.getElementById('root') if (rootElement) { const root = createRoot(rootElement) root.render() } ``` -------------------------------- ### Creating a Form Instance Source: https://tanstack.com/form/latest/docs/framework/react/guides/basic-concepts.md Illustrates how to create a `Form` instance using the `useForm` hook, either with pre-defined form options or standalone. ```APIDOC ## Creating a Form Instance ### Description This section explains how to instantiate a form using the `useForm` hook, which can accept `formOptions` or be configured directly. ### Method `useForm(options)` ### Endpoint N/A (Hook) ### Parameters #### Request Body - **defaultValues** (object) - Required - The default values for the form fields. - **onSubmit** (function) - Required - A function that is called when the form is submitted. It receives an object with the form `value`. - **...formOpts** (object) - Optional - Spreads properties from `formOptions`. ### Request Example (with formOptions) ```tsx const form = useForm({ ...formOpts, onSubmit: async ({ value }) => { // Do something with form data console.log(value) }, }) ``` ### Request Example (standalone) ```tsx interface User { firstName: string lastName: string hobbies: Array } const defaultUser: User = { firstName: '', lastName: '', hobbies: [] } const form = useForm({ defaultValues: defaultUser, onSubmit: async ({ value }) => { // Do something with form data console.log(value) }, }) ``` ### Response N/A (Returns a Form instance) ``` -------------------------------- ### Form Options Configuration Source: https://tanstack.com/form/latest/docs/framework/react/guides/basic-concepts.md Demonstrates how to create reusable form configuration options using `formOptions` with default values. ```APIDOC ## Form Options Configuration ### Description This section shows how to define shared configuration options for your forms, including setting default values. ### Method `formOptions(options)` ### Endpoint N/A (Library function) ### Parameters #### Request Body - **defaultValues** (object) - Required - The default values for the form fields. ### Request Example ```tsx interface User { firstName: string lastName: string hobbies: Array } const defaultUser: User = { firstName: '', lastName: '', hobbies: [] } const formOpts = formOptions({ defaultValues: defaultUser, }) ``` ### Response N/A (Returns configuration object) ``` -------------------------------- ### Validate Array Fields Starting From Index Source: https://tanstack.com/form/latest/docs/reference/classes/FormApi.md Use `validateArrayFieldsStartingFrom` to validate elements of an array field starting from a specific index. This is useful for partial validation of large arrays. ```typescript validateArrayFieldsStartingFrom( field, index, cause ): Promise; ``` -------------------------------- ### Instantiate FormApi Source: https://tanstack.com/form/latest/docs/reference/classes/FormApi.md Demonstrates how to construct a new FormApi instance with optional form options. This is typically handled by framework hooks, but can be done manually. ```typescript new FormApi(opts?) ``` -------------------------------- ### Setting up a Form with Custom Components Source: https://tanstack.com/form/latest/docs/framework/react/guides/form-composition.md Demonstrates how to create a form hook with custom field and form components, and then use it within an `AppForm` wrapper. The `AppForm` component provides the necessary context for the form. ```tsx const { useAppForm, withForm } = createFormHook({ fieldComponents: {}, formComponents: { SubscribeButton, }, fieldContext, formContext, }) function App() { const form = useAppForm({ defaultValues: { firstName: 'John', lastName: 'Doe', }, }) return ( // Notice the `AppForm` component wrapper; `AppForm` provides the required context ) } ``` -------------------------------- ### Instantiate FieldApi Source: https://tanstack.com/form/latest/docs/reference/classes/FieldApi.md Demonstrates how to create a new FieldApi instance directly. This is typically handled by framework hooks, but can be done manually if needed. ```typescript new FieldApi(opts) ``` -------------------------------- ### state Accessor Source: https://tanstack.com/form/latest/docs/reference/classes/FormApi.md Gets the current state of the form. ```APIDOC ## state ### Description Gets the current state of the form. ### Get Signature ```ts get state(): FormState; ``` ### Returns [`FormState`](../interfaces/FormState.md) ### Defined in [packages/form-core/src/FormApi.ts:1049](https://github.com/TanStack/form/blob/main/packages/form-core/src/FormApi.ts#L1049) ``` -------------------------------- ### formId Accessor Source: https://tanstack.com/form/latest/docs/reference/classes/FormApi.md Gets the unique identifier for the form. ```APIDOC ## formId ### Description Gets the unique identifier for the form. ### Get Signature ```ts get formId(): string; ``` ### Returns `string` ### Defined in [packages/form-core/src/FormApi.ts:1628](https://github.com/TanStack/form/blob/main/packages/form-core/src/FormApi.ts#L1628) ``` -------------------------------- ### Get Field Metadata Source: https://tanstack.com/form/latest/docs/reference/classes/FieldApi.md Retrieves the metadata associated with a field. This is an implementation of FieldLikeAPI.getMeta. ```typescript FieldLikeAPI.getMeta ``` -------------------------------- ### Form-Level Listeners Source: https://tanstack.com/form/latest/docs/framework/react/guides/listeners.md Illustrates how to configure listeners at the form level to handle events like `onMount` and `onSubmit`, and how `onChange` and `onBlur` events propagate. ```APIDOC ## Form-Level Listeners ### Description Configures listeners at the form level to capture global form events like mount, submit, and changes across all fields. ### Method N/A (Configuration within `useForm`) ### Endpoint N/A ### Parameters #### Form Configuration - **listeners** (object) - Optional - An object containing form-level event listener functions. - **onMount** (function) - Callback function executed when the form is mounted. Receives `formApi`. - **onSubmit** (function) - Callback function executed when the form is submitted. Receives `formApi`. - **onChange** (function) - Callback function executed when any field's value changes. Receives `formApi` and `fieldApi`. - **onBlur** (function) - Callback function executed when any field loses focus. Receives `formApi` and `fieldApi`. - **onChangeDebounceMs** (number) - Optional - Debounce time in milliseconds for the form-level `onChange` event. - **onBlurDebounceMs** (number) - Optional - Debounce time in milliseconds for the form-level `onBlur` event. ### Request Example ```tsx const form = useForm({ listeners: { onMount: ({ formApi }) => { // custom logging service loggingService('mount', formApi.state.values) }, onChange: ({ formApi, fieldApi }) => { // autosave logic if (formApi.state.isValid) { formApi.handleSubmit() } // fieldApi represents the field that triggered the event. console.log(fieldApi.name, fieldApi.state.value) }, onChangeDebounceMs: 500, }, }) ``` ### Response N/A (Side effects are triggered) ### Error Handling N/A ``` -------------------------------- ### FieldApi State Accessor Source: https://tanstack.com/form/latest/docs/reference/classes/FieldApi.md Get the current state of the field. This accessor returns a FieldLikeState object. ```typescript get state(): FieldLikeState; ``` -------------------------------- ### Create and Render a Form with Solid Source: https://tanstack.com/form/latest/docs/overview.md Use `createForm` to initialize a form with default values and an onSubmit handler. Render form fields and a submit button using Solid's JSX syntax. The `form.Field` component handles individual fields, and `form.Subscribe` allows subscribing to form state changes. ```typescript /* @refresh reload */ import { render } from 'solid-js/web' import { createForm } from '@tanstack/solid-form' import { FieldInfo } from './FieldInfo.tsx'; function App() { const form = createForm(() => ({ defaultValues: { firstName: '', lastName: '', }, onSubmit: async ({ value }) => { // Do something with form data console.log(value) }, })) return (

Simple Form Example

{ e.preventDefault() e.stopPropagation() form.handleSubmit() }} >
{/* A type-safe field component*/} !value ? 'A first name is required' : value.length < 3 ? 'First name must be at least 3 characters' : undefined, onChangeAsyncDebounceMs: 500, onChangeAsync: async ({ value }) => { await new Promise((resolve) => setTimeout(resolve, 1000)) return ( value.includes('error') && 'No "error" allowed in first name' ) }, }} children={(field) => { // Avoid hasty abstractions. Render props are great! return ( <> field().handleChange(e.target.value)} /> ) }} />
( <> field().handleChange(e.target.value)} /> )} />
({ canSubmit: state.canSubmit, isSubmitting: state.isSubmitting, })} children={(state) => { return ( ) }} />
) } const root = document.getElementById('root') render(() => , root!) ``` -------------------------------- ### Get Field Value Source: https://tanstack.com/form/latest/docs/reference/classes/FieldApi.md Retrieves the current value of the field. Use field.state.value instead as this method is deprecated. ```typescript getValue(): TData; ``` -------------------------------- ### Create Form Instance with onSubmit Handler Source: https://tanstack.com/form/latest/docs/framework/react/guides/basic-concepts.md Demonstrates creating a Form instance using the `useForm` hook, which is part of the form options. The `onSubmit` function is provided to handle form submission data. ```typescript const form = useForm({ ...formOpts, onSubmit: async ({ value }) => { // Do something with form data console.log(value) }, }) ``` -------------------------------- ### Get Form State Signature Source: https://tanstack.com/form/latest/docs/reference/classes/FormApi.md Accessor to retrieve the current state of the form. Returns the FormState object. ```typescript get state(): FormState; ``` -------------------------------- ### Returning Number Errors from Validators Source: https://tanstack.com/form/latest/docs/framework/react/guides/custom-errors.md Illustrates using numbers as error values, for example, to indicate a required quantity. ```APIDOC ## Returning Number Errors ### Description Validates the age field, returning the difference needed to reach the minimum age if the current age is below 18. ### Method N/A (Component Configuration) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```tsx (value < 18 ? 18 - value : undefined), }} /> ``` ### Response #### Success Response (200) N/A #### Response Example N/A ## Displaying Number Errors ### Description Shows how to display a numeric error value, such as the number of years remaining to meet an age requirement. ### Method N/A (UI Rendering) ### Endpoint N/A ### Parameters None ### Request Example ```tsx // TypeScript knows the error is a number based on your validator
You need {field.state.meta.errors[0]} more years to be eligible
``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### validateArrayFieldsStartingFrom Source: https://tanstack.com/form/latest/docs/reference/classes/FormApi.md Validates the children of a specified array field starting from a given index. This is useful for partial validation of array data. ```APIDOC ## validateArrayFieldsStartingFrom ### Description Validates the children of a specified array in the form starting from a given index until the end using the correct handlers for a given validation type. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **field** (TField) - Required - The identifier of the array field. - **index** (number) - Required - The starting index for validation. - **cause** (ValidationCause) - Required - The reason for the validation. ``` -------------------------------- ### getFieldValue Source: https://tanstack.com/form/latest/docs/reference/classes/FormApi.md Gets the value of the specified field. This method is part of the FormApi and is used to retrieve the current value of a form field. ```APIDOC ## getFieldValue() ### Description Gets the value of the specified field. Mirrors `getFieldMeta` for fields. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **field** (TField) - Required - The name or path of the field to get the value for. ### Returns [`DeepValue`](../type-aliases/DeepValue.md) ### Example ```ts const fieldValue = formApi.getFieldValue('myField'); ``` ``` -------------------------------- ### Get Field Value Source: https://tanstack.com/form/latest/docs/reference/classes/FormApi.md Retrieves the value of a specific field from the form data. Use this to access individual field states. ```typescript getFieldValue(field): DeepValue; ``` -------------------------------- ### FieldApi Constructor Source: https://tanstack.com/form/latest/docs/reference/classes/FieldApi.md Initializes a new FieldApi instance. While you can instantiate this class directly, it's generally recommended to use framework-specific hooks like `useField` or `createField` which handle the creation and integration with your reactivity system. ```APIDOC ## Constructor FieldApi ### Description Initializes a new `FieldApi` instance. ### Parameters #### opts - **opts** (`FieldApiOptions`) - Required - An object containing the configuration options for the `FieldApi` instance. ``` -------------------------------- ### getFormGroupMeta Source: https://tanstack.com/form/latest/docs/reference/classes/FormApi.md Gets the derived meta of the form group registered at the given name. This method is useful for inspecting the state of a form group. ```APIDOC ## getFormGroupMeta() ### Description Gets the derived `meta` of the form group registered at the given name. Mirrors `getFieldMeta` for fields. Returns `undefined` if no `FormGroupApi` with that name is currently mounted. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **name** (string) - Required - The name of the form group. ### Returns [`AnyFormGroupMeta`](../type-aliases/AnyFormGroupMeta.md) | `undefined` ### Example ```ts const groupMeta = formApi.getFormGroupMeta('myGroup'); ``` ```