fix(form-core): create complete field meta on setFieldValue for uninitialized fields #2245
main fromrefs/pull/2245/head·opened What & why#
FormApi.setFieldValue on a field that has never mounted built its meta with (prev) => ({ ...prev, isTouched, isDirty, errorMap }) where prev is undefined, producing a partial meta object missing required fields declared on AnyFieldLikeMetaBase (isValidating, isBlurred, errorSourceMap, _arrayVersion, _pendingValidationsCount). This is the incomplete-meta problem reported in #1078.
Fix#
Default the updater argument to the shared defaultFieldMeta:
(prev = defaultFieldMeta) => ({ ...prev, isTouched, isDirty, errorMap })
in packages/form-core/src/FormApi.ts, mirroring the exact pattern already used at the two other setFieldMeta call sites in the same file. The meta created for a never-mounted field is now structurally identical to a mounted field's.
Tests#
packages/form-core/tests/FormApi.spec.ts — added a failing-first test asserting the created meta is complete (isValidating: false, isBlurred: false, errors: [], errorSourceMap: {}, no undefined fields) after setFieldValue on an uninitialized field. Confirmed red on original code → green after the fix.
Full @tanstack/form-core suite: 504 passed / 3 todo, no type errors.
Closes #1078
Summary by CodeRabbit#
Bug Fixes
- Updated field value handling so unmounted (conditional) fields receive fully initialized metadata.
- Ensured validation and interaction state (including error tracking) are no longer left unset when updating field values before mounting.
Tests
- Added a test covering
setFieldValueon an unmounted field, verifying default error arrays/maps and related flags are consistently populated.
- Added a test covering
- 1
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/form-core/tests/FormApi.spec.ts (1)
102-110: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAlso assert touched/dirty state preservation.
The production change explicitly preserves
isTouchedandisDirty, but this regression test does not verify either field.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/form-core/tests/FormApi.spec.ts` around lines 102 - 110, Extend the metadata assertions in FormApi.spec.ts to verify that the preserved isTouched and isDirty values remain defined and retain their expected state alongside isValidating, isBlurred, and errorSourceMap.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/form-core/tests/FormApi.spec.ts`: - Line 92: Update the test around form.mount() to capture its returned cleanup function and invoke that cleanup in a finally block, ensuring listeners are removed even when the test fails. --- Nitpick comments: In `@packages/form-core/tests/FormApi.spec.ts`: - Around line 102-110: Extend the metadata assertions in FormApi.spec.ts to verify that the preserved isTouched and isDirty values remain defined and retain their expected state alongside isValidating, isBlurred, and errorSourceMap.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
8aef8188-71ed-4945-96e1-c8181d1d2a35📥 Commits
Reviewing files that changed from the base of the PR and between 5d1128141a705ebb24ade1275b3117bb4c8b1bdc and 81c50db9136820c7981302cc2fa398cf781303c2.
📒 Files selected for processing (2)
packages/form-core/src/FormApi.tspackages/form-core/tests/FormApi.spec.ts
packages/form-core/tests/FormApi.spec.ts line 92@@ -83,3 +83,10 @@8383 })8484 })858586+ it('should create complete meta when setFieldValue targets an uninitialized field', () => {87+ const form = new FormApi({88+ defaultValues: {89+ availableFor: 'longStay',90+ } as { availableFor: string; fees?: number },91+ })92+ form.mount()🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Clean up the form mount in the test.
form.mount()registers listeners and returns a cleanup function. Capture and invoke it infinallyto prevent cross-test listener leaks.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/form-core/tests/FormApi.spec.ts` at line 92, Update the test around form.mount() to capture its returned cleanup function and invoke that cleanup in a finally block, ensuring listeners are removed even when the test fails.Added the touched/dirty assertions from the review summary in 51d4103 (verified the runtime values by running the test). On the mount cleanup: skipping this one — the suite has ~136
form.mount()calls and none capture the cleanup, and the event-client listeners are keyed by each form's unique_formId, so there's no cross-test interference. Making just this test different from the rest of the file felt inconsistent; happy to do a suite-wide cleanup pass in a separate PR if maintainers want it.Traced
setFieldMetato confirm this actually reproduces the bug the way I expected. It callsfunctionalUpdate(updater, prev.fieldMetaBase[field] as never), so for a field that's never been touched, the updater genuinely gets called withundefined, not some partial object. Before this fix,prev?.errorMapmade that safe from throwing, but{...prev, isTouched: true, isDirty: true, errorMap: {...}}on anundefinedprevspreads to nothing, so the resulting meta only ever hadisTouched,isDirtyanderrorMapset, every other documented field (isValidating,isBlurred,isPristine,isValid,errors,errorSourceMap, etc.) came outundefinedinstead of the real default.Using
defaultFieldMetaas the parameter default is the right fix and it's not a new idiom,bumpArrayVersionin metaHelper.ts already doesformApi.getFieldMeta(field) ?? defaultFieldMetafor the same reason, so this bringssetFieldValuein line with how the rest of the file already handles a possibly-uninitialized meta object.Test directly checks the fields that would have silently come back
undefinedbefore (isValidating,isBlurred,errorSourceMap), which is the part that actually matters here, a shallow check on justisTouched/isDirtywould have passed both before and after the fix and not caught anything.xianjianlf2(GitHub profile, opens in a new tab) linked this to fix #1078
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
b230de24-9dc8-4de4-b591-252bb4e76abf📥 Commits
Reviewing files that changed from the base of the PR and between 81c50db9136820c7981302cc2fa398cf781303c2 and 51d41039231a282ae8ecd9620052fc359695c628.
📒 Files selected for processing (1)
packages/form-core/tests/FormApi.spec.ts🚧 Files skipped from review as they are similar to previous changes (1)
📝 Walkthrough
Walkthrough#
FormApi.setFieldValuenow creates complete metadata when updating an unmounted field, including default error-related properties. A regression test verifies the resulting metadata shape and defined validation fields.Changes#
Field metadata initialization
packages/form-core/src/FormApi.ts,packages/form-core/tests/FormApi.spec.tsdefaultFieldMeta, while tests verify complete metadata for an unmounted field.Estimated code review effort: 1 (Trivial) | ~5 minutes
Possibly related PRs
setFieldValuemetadata initialization and related default metadata keys.🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
#1078by ensuring setFieldValue initializes complete meta, including errors, for unmounted fields.✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share