Skip to content
Source
Sign inSign up
TanStack/form

fix(form-core): create complete field meta on setFieldValue for uninitialized fields #2245

Openxianjianlf2(GitHub profile, opens in a new tab)wants to merge 2 commits intomain fromrefs/pull/2245/headopened

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 setFieldValue on an unmounted field, verifying default error arrays/maps and related flags are consistently populated.
    1. Review Change Stack

      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)
      • packages/form-core/tests/FormApi.spec.ts

      📝 Walkthrough

      Walkthrough

      FormApi.setFieldValue now 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

      Layer / File(s)Summary
      Default metadata update and regression coverage
      packages/form-core/src/FormApi.ts, packages/form-core/tests/FormApi.spec.ts
      The metadata updater defaults missing previous metadata to defaultFieldMeta, while tests verify complete metadata for an unmounted field.

      Estimated code review effort: 1 (Trivial) | ~5 minutes

      Possibly related PRs

      • TanStack/form#2143: Updates setFieldValue metadata initialization and related default metadata keys.
      🚥 Pre-merge checks | ✅ 5
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly and specifically summarizes the main fix in form-core.
      Description check✅ PassedThe description covers the bug, fix, and tests, but it does not follow the repository's exact template sections.
      Linked Issues check✅ PassedThe change addresses #1078 by ensuring setFieldValue initializes complete meta, including errors, for unmounted fields.
      Out of Scope Changes check✅ PassedThe PR only changes the targeted FormApi logic and adds a regression test, with no unrelated scope creep.
      Docstring Coverage✅ PassedNo functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      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
      Comment `@coderabbitai help` to get the list of available commands.
    2. Actionable comments posted: 1

      🧹 Nitpick comments (1)
      packages/form-core/tests/FormApi.spec.ts (1)

      102-110: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Also assert touched/dirty state preservation.

      The production change explicitly preserves isTouched and isDirty, 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.ts
      • packages/form-core/tests/FormApi.spec.ts
      packages/form-core/tests/FormApi.spec.ts line 92
      @@ -83,3 +83,10 @@
      8383 })
      8484 })
      8585
      86+ 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 in finally to 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.

    3. Traced setFieldMeta to confirm this actually reproduces the bug the way I expected. It calls functionalUpdate(updater, prev.fieldMetaBase[field] as never), so for a field that's never been touched, the updater genuinely gets called with undefined, not some partial object. Before this fix, prev?.errorMap made that safe from throwing, but {...prev, isTouched: true, isDirty: true, errorMap: {...}} on an undefined prev spreads to nothing, so the resulting meta only ever had isTouched, isDirty and errorMap set, every other documented field (isValidating, isBlurred, isPristine, isValid, errors, errorSourceMap, etc.) came out undefined instead of the real default.

      Using defaultFieldMeta as the parameter default is the right fix and it's not a new idiom, bumpArrayVersion in metaHelper.ts already does formApi.getFieldMeta(field) ?? defaultFieldMeta for the same reason, so this brings setFieldValue in 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 undefined before (isValidating, isBlurred, errorSourceMap), which is the part that actually matters here, a shallow check on just isTouched/isDirty would have passed both before and after the fix and not caught anything.

Sign in to join this conversation.