Skip to content

Commit ea9d5fb

Browse files
authored
fix(FieldApi): fix race condition when using onChangeListenTo
1 parent 4822f00 commit ea9d5fb

2 files changed

Lines changed: 15 additions & 9 deletions

File tree

packages/form-core/src/FieldApi.ts

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1854,18 +1854,23 @@ export class FieldApi<
18541854
// Check if there are actual async validators to run before setting isValidating
18551855
// This prevents unnecessary re-renders when there are no async validators
18561856
// See: https://github.com/TanStack/form/issues/1130
1857-
const hasAsyncValidators =
1858-
validates.some((v) => v.validate) ||
1859-
linkedFieldValidates.some((v) => v.validate)
1857+
const hasAsyncValidators = validates.some((v) => v.validate)
1858+
const linkedFieldsWithAsyncValidators = linkedFieldValidates.some((v) => v.validate) ? Array.from(
1859+
new Set(
1860+
linkedFieldValidates
1861+
.filter((v) => v.validate)
1862+
.map((v) => v.field),
1863+
),
1864+
) : []
18601865

18611866
if (hasAsyncValidators) {
18621867
if (!this.state.meta.isValidating) {
18631868
this.setMeta((prev) => ({ ...prev, isValidating: true }))
18641869
}
1870+
}
18651871

1866-
for (const linkedField of linkedFields) {
1867-
linkedField.setMeta((prev) => ({ ...prev, isValidating: true }))
1868-
}
1872+
for (const linkedField of linkedFieldsWithAsyncValidators) {
1873+
linkedField.setMeta((prev) => ({ ...prev, isValidating: true }))
18691874
}
18701875

18711876
const validateFieldAsyncFn = (
@@ -1980,10 +1985,10 @@ export class FieldApi<
19801985
// Only reset isValidating if we set it to true earlier
19811986
if (hasAsyncValidators) {
19821987
this.setMeta((prev) => ({ ...prev, isValidating: false }))
1988+
}
19831989

1984-
for (const linkedField of linkedFields) {
1985-
linkedField.setMeta((prev) => ({ ...prev, isValidating: false }))
1986-
}
1990+
for (const linkedField of linkedFieldsWithAsyncValidators) {
1991+
linkedField.setMeta((prev) => ({ ...prev, isValidating: false }))
19871992
}
19881993

19891994
return results.filter(Boolean)

packages/form-core/tests/FormApi.spec.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3047,6 +3047,7 @@ describe('form api', () => {
30473047

30483048
expect.soft(form.state.isFieldsValidating).toBe(false)
30493049
expect.soft(form.state.isFieldsValid).toBe(true)
3050+
expect.soft(form.state.isValid).toBe(true)
30503051
expect.soft(form.state.canSubmit).toBe(true)
30513052

30523053
vi.useRealTimers()

0 commit comments

Comments
 (0)