Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/shy-otters-give.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/form-core': patch
---

fix: create fieldMeta on async validation for fields with errors
20 changes: 12 additions & 8 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1879,16 +1879,20 @@ export class FormApi<
}
const errorMapKey = getErrorMapKey(validateObj.cause)

for (const field of Object.keys(
this.state.fieldMeta,
) as DeepKeys<TFormData>[]) {
if (this.baseStore.state.fieldMetaBase[field] === undefined) {
const allFieldsToProcess = new Set([
...Object.keys(this.state.fieldMeta),
...Object.keys(fieldErrorsFromFormValidators || {}),
] as DeepKeys<TFormData>[])

for (const field of allFieldsToProcess) {
if (
this.baseStore.state.fieldMetaBase[field] === undefined &&
!fieldErrorsFromFormValidators?.[field]
) {
continue
}

const fieldMeta = this.getFieldMeta(field)
if (!fieldMeta) continue

const fieldMeta = this.getFieldMeta(field) ?? defaultFieldMeta
const {
errorMap: currentErrorMap,
errorSourceMap: currentErrorMapSource,
Expand All @@ -1910,7 +1914,7 @@ export class FormApi<
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
currentErrorMap?.[errorMapKey] !== newErrorValue
) {
this.setFieldMeta(field, (prev) => ({
this.setFieldMeta(field, (prev = defaultFieldMeta) => ({
...prev,
errorMap: {
...prev.errorMap,
Expand Down
31 changes: 31 additions & 0 deletions packages/form-core/tests/FormApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1873,6 +1873,37 @@ describe('form api', () => {
expect(formSubmit).toHaveBeenCalledOnce()
})

it('should create field meta from form async submit validation errors', async () => {
vi.useFakeTimers()

const form = new FormApi({
defaultValues: {
age: 0,
},
validators: {
onSubmitAsync: async ({ value }) => {
await sleep(1)
return value.age > 0
? undefined
: { fields: { age: 'age must be greater than 0' } }
},
},
asyncDebounceMs: 1,
})

form.mount()

expect(form.state.fieldMeta.age).toBeUndefined()

form.handleSubmit()
await vi.runAllTimersAsync()

expect(form.state.fieldMeta.age).toBeDefined()
expect(form.state.fieldMeta.age?.errorMap.onSubmit).toBe(
'age must be greater than 0',
)
})

it('should run all types of async validation on fields during submit', async () => {
vi.useFakeTimers()

Expand Down