Skip to content

feat(core): form listeners #1261

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 38 additions & 4 deletions docs/framework/react/guides/listeners.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ In this example, when the user changes the country, the selected province needs

Events that can be "listened" to are:

- onChange
- onBlur
- onMount
- onSubmit
- `onChange`
- `onBlur`
- `onMount`
- `onSubmit`

```tsx
function App() {
Expand Down Expand Up @@ -89,3 +89,37 @@ We enable an easy method for debouncing your listeners by adding a `onChangeDebo
)}
</form.Field>
```

### Form listeners

At a higher level, listeners are also available at the form level, allowing you access to the `onMount` and `onSubmit` events, and having `onChange` and `onBlur` propagated to all the form's children.

`onMount` and `onSubmit` listeners have to following props:

- `formApi`

`onChange` and `onBlur` listeners have access to:

- `fieldApi`
- `formApi`

```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)
},
},
})
```
9 changes: 9 additions & 0 deletions packages/form-core/src/FieldApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1704,6 +1704,10 @@ export class FieldApi<

private triggerOnBlurListener() {
const debounceMs = this.options.listeners?.onBlurDebounceMs
this.form.options.listeners?.onBlur?.({
formApi: this.form,
fieldApi: this,
})

if (debounceMs && debounceMs > 0) {
if (this.timeoutIds.listeners.blur) {
Expand All @@ -1727,6 +1731,11 @@ export class FieldApi<
private triggerOnChangeListener() {
const debounceMs = this.options.listeners?.onChangeDebounceMs

this.form.options.listeners?.onChange?.({
formApi: this.form,
fieldApi: this,
})

if (debounceMs && debounceMs > 0) {
if (this.timeoutIds.listeners.change) {
clearTimeout(this.timeoutIds.listeners.change)
Expand Down
103 changes: 102 additions & 1 deletion packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ import type {
StandardSchemaV1Issue,
TStandardSchemaValidatorValue,
} from './standardSchemaValidator'
import type { AnyFieldMeta, AnyFieldMetaBase, FieldApi } from './FieldApi'
import type {
AnyFieldApi,
AnyFieldMeta,
AnyFieldMetaBase,
FieldApi,
} from './FieldApi'
import type {
FormValidationError,
FormValidationErrorMap,
Expand Down Expand Up @@ -233,6 +238,81 @@ export interface FormTransform<
deps: unknown[]
}

export interface FormListeners<
TFormData,
TOnMount extends undefined | FormValidateOrFn<TFormData>,
TOnChange extends undefined | FormValidateOrFn<TFormData>,
TOnChangeAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
TOnBlur extends undefined | FormValidateOrFn<TFormData>,
TOnBlurAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
TOnSubmit extends undefined | FormValidateOrFn<TFormData>,
TOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
TOnServer extends undefined | FormAsyncValidateOrFn<TFormData>,
TSubmitMeta = never,
> {
onChange?: (props: {
formApi: FormApi<
TFormData,
TOnMount,
TOnChange,
TOnChangeAsync,
TOnBlur,
TOnBlurAsync,
TOnSubmit,
TOnSubmitAsync,
TOnServer,
TSubmitMeta
>
fieldApi: AnyFieldApi
}) => void

onBlur?: (props: {
formApi: FormApi<
TFormData,
TOnMount,
TOnChange,
TOnChangeAsync,
TOnBlur,
TOnBlurAsync,
TOnSubmit,
TOnSubmitAsync,
TOnServer,
TSubmitMeta
>
fieldApi: AnyFieldApi
}) => void

onMount?: (props: {
formApi: FormApi<
TFormData,
TOnMount,
TOnChange,
TOnChangeAsync,
TOnBlur,
TOnBlurAsync,
TOnSubmit,
TOnSubmitAsync,
TOnServer,
TSubmitMeta
>
}) => void

onSubmit?: (props: {
formApi: FormApi<
TFormData,
TOnMount,
TOnChange,
TOnChangeAsync,
TOnBlur,
TOnBlurAsync,
TOnSubmit,
TOnSubmitAsync,
TOnServer,
TSubmitMeta
>
}) => void
}

/**
* An object representing the options for a form.
*/
Expand Down Expand Up @@ -299,6 +379,22 @@ export interface FormOptions<
*/
onSubmitMeta?: TSubmitMeta

/**
* form level listeners
*/
listeners?: FormListeners<
TFormData,
TOnMount,
TOnChange,
TOnChangeAsync,
TOnBlur,
TOnBlurAsync,
TOnSubmit,
TOnSubmitAsync,
TOnServer,
TSubmitMeta
>

/**
* A function to be called when the form is submitted, what should happen once the user submits a valid form returns `any` or a promise `Promise<any>`
*/
Expand Down Expand Up @@ -1049,6 +1145,9 @@ export class FormApi<
cleanupFieldMetaDerived()
cleanupStoreDerived()
}

this.options.listeners?.onMount?.({ formApi: this })

const { onMount } = this.options.validators || {}
if (!onMount) return cleanup
this.validateSync('mount')
Expand Down Expand Up @@ -1676,6 +1775,8 @@ export class FormApi<
)
})

this.options.listeners?.onSubmit?.({ formApi: this })

try {
// Run the submit code
await this.options.onSubmit?.({
Expand Down
140 changes: 139 additions & 1 deletion packages/form-core/tests/FormApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
import { z } from 'zod'
import { FieldApi, FormApi } from '../src/index'
import { sleep } from './utils'
import type { AnyFieldApi, AnyFormApi } from '../src/index'

describe('form api', () => {
it('should get default form state when default values are passed', () => {
Expand Down Expand Up @@ -1956,7 +1957,144 @@ describe('form api', () => {
expect(form.state.errors).toStrictEqual(['first name is required'])
})

it('should run listener onSubmit', async () => {
it('should run the form listener onSubmit', async () => {
let triggered!: string
const form = new FormApi({
defaultValues: {
name: 'test',
},
listeners: {
onSubmit: ({ formApi }) => {
triggered = formApi.state.values.name
},
},
})

form.mount()
await form.handleSubmit()

expect(triggered).toStrictEqual('test')
})

it('should run the form listener onMount', async () => {
let triggered!: string
const form = new FormApi({
defaultValues: {
name: 'test',
},
listeners: {
onMount: ({ formApi }) => {
triggered = formApi.state.values.name
},
},
})

form.mount()

expect(triggered).toStrictEqual('test')
})

it('should run the form listener onChange', async () => {
let fieldApiCheck!: AnyFieldApi
let formApiCheck!: AnyFormApi

const form = new FormApi({
defaultValues: {
name: '',
},
listeners: {
onChange: ({ fieldApi, formApi }) => {
fieldApiCheck = fieldApi

formApiCheck = formApi as any
},
},
})
form.mount()

const field = new FieldApi({
form,
name: 'name',
})
field.mount()
field.setValue('newTest')

expect(fieldApiCheck.state.value).toStrictEqual('newTest')
expect(formApiCheck.state.values.name).toStrictEqual('newTest')
})

it('should run the form listener onChange when the field array is changed', () => {
let arr!: any

const form = new FormApi({
defaultValues: {
items: ['one', 'two'],
age: 0,
},
listeners: {
onChange: ({ fieldApi }) => {
arr = fieldApi.state.value
},
},
})
form.mount()

const field = new FieldApi({
form,
name: 'items',
})
field.mount()

field.removeValue(1)
expect(arr).toStrictEqual(['one'])

field.replaceValue(0, 'start')
expect(arr).toStrictEqual(['start'])

field.pushValue('end')
expect(arr).toStrictEqual(['start', 'end'])

field.insertValue(1, 'middle')
expect(arr).toStrictEqual(['start', 'middle', 'end'])

field.swapValues(0, 2)
expect(arr).toStrictEqual(['end', 'middle', 'start'])

field.moveValue(0, 1)
expect(arr).toStrictEqual(['middle', 'end', 'start'])
})

it('should run the form listener onBlur', async () => {
let fieldApiCheck!: AnyFieldApi
let formApiCheck!: AnyFormApi

const form = new FormApi({
defaultValues: {
name: 'test',
age: 0,
},
listeners: {
onBlur: ({ fieldApi, formApi }) => {
fieldApiCheck = fieldApi

formApiCheck = formApi as any
},
},
})
form.mount()

const field = new FieldApi({
form,
name: 'name',
})
field.mount()
field.handleBlur()

expect(fieldApiCheck.state.value).toStrictEqual('test')
expect(formApiCheck.state.values.name).toStrictEqual('test')
})

it('should run the field listener onSubmit', async () => {
const form = new FormApi({
defaultValues: {
name: 'test',
Expand Down