Skip to content

feat(core): debounced form listeners #1463

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 2 commits into from
Apr 27, 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
3 changes: 2 additions & 1 deletion docs/framework/react/guides/listeners.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ We enable an easy method for debouncing your listeners by adding a `onChangeDebo

### 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.
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. Form-level listeners can also be debounced in the same way as previously discussed.

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

Expand Down Expand Up @@ -120,6 +120,7 @@ const form = useForm({
// fieldApi represents the field that triggered the event.
console.log(fieldApi.name, fieldApi.state.value)
},
onChangeDebounceMs: 500,
},
})
```
57 changes: 43 additions & 14 deletions packages/form-core/src/FieldApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -978,6 +978,7 @@ export class FieldApi<
timeoutIds: {
validations: Record<ValidationCause, ReturnType<typeof setTimeout> | null>
listeners: Record<ListenerCause, ReturnType<typeof setTimeout> | null>
formListeners: Record<ListenerCause, ReturnType<typeof setTimeout> | null>
}

/**
Expand Down Expand Up @@ -1011,6 +1012,7 @@ export class FieldApi<
this.timeoutIds = {
validations: {} as Record<ValidationCause, never>,
listeners: {} as Record<ListenerCause, never>,
formListeners: {} as Record<ListenerCause, never>,
}

this.store = new Derived({
Expand Down Expand Up @@ -1703,13 +1705,27 @@ export class FieldApi<
}

private triggerOnBlurListener() {
const debounceMs = this.options.listeners?.onBlurDebounceMs
this.form.options.listeners?.onBlur?.({
formApi: this.form,
fieldApi: this,
})
const formDebounceMs = this.form.options.listeners?.onBlurDebounceMs
if (formDebounceMs && formDebounceMs > 0) {
if (this.timeoutIds.formListeners.blur) {
clearTimeout(this.timeoutIds.formListeners.blur)
}

this.timeoutIds.formListeners.blur = setTimeout(() => {
this.form.options.listeners?.onBlur?.({
formApi: this.form,
fieldApi: this,
})
}, formDebounceMs)
} else {
this.form.options.listeners?.onBlur?.({
formApi: this.form,
fieldApi: this,
})
}

if (debounceMs && debounceMs > 0) {
const fieldDebounceMs = this.options.listeners?.onBlurDebounceMs
if (fieldDebounceMs && fieldDebounceMs > 0) {
if (this.timeoutIds.listeners.blur) {
clearTimeout(this.timeoutIds.listeners.blur)
}
Expand All @@ -1719,7 +1735,7 @@ export class FieldApi<
value: this.state.value,
fieldApi: this,
})
}, debounceMs)
}, fieldDebounceMs)
} else {
this.options.listeners?.onBlur?.({
value: this.state.value,
Expand All @@ -1729,14 +1745,27 @@ export class FieldApi<
}

private triggerOnChangeListener() {
const debounceMs = this.options.listeners?.onChangeDebounceMs
const formDebounceMs = this.form.options.listeners?.onChangeDebounceMs
if (formDebounceMs && formDebounceMs > 0) {
if (this.timeoutIds.formListeners.blur) {
clearTimeout(this.timeoutIds.formListeners.blur)
}

this.form.options.listeners?.onChange?.({
formApi: this.form,
fieldApi: this,
})
this.timeoutIds.formListeners.blur = setTimeout(() => {
this.form.options.listeners?.onChange?.({
formApi: this.form,
fieldApi: this,
})
}, formDebounceMs)
} else {
this.form.options.listeners?.onChange?.({
formApi: this.form,
fieldApi: this,
})
}

if (debounceMs && debounceMs > 0) {
const fieldDebounceMs = this.options.listeners?.onChangeDebounceMs
if (fieldDebounceMs && fieldDebounceMs > 0) {
if (this.timeoutIds.listeners.change) {
clearTimeout(this.timeoutIds.listeners.change)
}
Expand All @@ -1746,7 +1775,7 @@ export class FieldApi<
value: this.state.value,
fieldApi: this,
})
}, debounceMs)
}, fieldDebounceMs)
} else {
this.options.listeners?.onChange?.({
value: this.state.value,
Expand Down
2 changes: 2 additions & 0 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ export interface FormListeners<
>
fieldApi: AnyFieldApi
}) => void
onChangeDebounceMs?: number

onBlur?: (props: {
formApi: FormApi<
Expand All @@ -281,6 +282,7 @@ export interface FormListeners<
>
fieldApi: AnyFieldApi
}) => void
onBlurDebounceMs?: number

onMount?: (props: {
formApi: FormApi<
Expand Down
62 changes: 62 additions & 0 deletions packages/form-core/tests/FormApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2064,6 +2064,39 @@ describe('form api', () => {
expect(arr).toStrictEqual(['middle', 'end', 'start'])
})

it('should debounce onChange listener', async () => {
vi.useFakeTimers()
const onChangeMock = vi.fn()

const form = new FormApi({
defaultValues: {
name: '',
},
listeners: {
onChange: onChangeMock,
onChangeDebounceMs: 500,
},
})
form.mount()

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

field.handleChange('first')
field.handleChange('second')
expect(onChangeMock).not.toHaveBeenCalled()

await vi.advanceTimersByTimeAsync(500)
expect(onChangeMock).toHaveBeenCalledTimes(1)
expect(onChangeMock).toHaveBeenCalledWith({
formApi: form,
fieldApi: field,
})
})

it('should run the form listener onBlur', async () => {
let fieldApiCheck!: AnyFieldApi
let formApiCheck!: AnyFormApi
Expand Down Expand Up @@ -2094,6 +2127,35 @@ describe('form api', () => {
expect(formApiCheck.state.values.name).toStrictEqual('test')
})

it('should debounce onBlur listener', async () => {
vi.useFakeTimers()
const onBlurMock = vi.fn()

const form = new FormApi({
defaultValues: {
name: '',
},
listeners: {
onBlur: onBlurMock,
onBlurDebounceMs: 500,
},
})
form.mount()

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

field.handleBlur()
field.handleBlur()
expect(onBlurMock).not.toHaveBeenCalled()

await vi.advanceTimersByTimeAsync(500)
expect(onBlurMock).toHaveBeenCalledTimes(1)
})

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