fix(form-core): preserve reset(newValues) when update() is called with stale options #2218
main fromrefs/pull/2218/head·opened Summary#
Fixes #1681 — form.reset(newValues) called inside onSubmit is ignored and the form reverts to its original default values.
Root cause#
reset(values) (with explicit new values) does two things:
- Updates
this.options.defaultValues = valuesin-place - Calls
this.baseStore.setState(...)with the new values
After the onSubmit promise resolves, React re-renders (because isSubmitting flipped back to false). The framework then calls formApi.update(opts) inside useIsomorphicLayoutEffect — where opts is the original options object captured in the render closure, still holding the pre-reset defaultValues.
Inside update():
oldOptions = this.options→ has the new defaultValues (set by reset)this.options = options→ overwrites back to original defaultValuesoptions.defaultValues !== oldOptions.defaultValues→true!this.state.isTouched→true(reset cleared touched state)shouldUpdateValues = true→ form values reset to original defaults ❌
Fix#
Add a private _defaultValuesOverridden flag on FormApi. When reset(values) is called with explicit values (and !keepDefaultValues), set the flag to true. In update(), if the flag is set, skip the shouldUpdateValues branch and preserve the defaultValues that reset() stored on this.options. The flag is cleared after one update() cycle so subsequent prop-driven defaultValues changes continue to work correctly.
Test plan#
- Added a new unit test in
packages/form-core/tests/FormApi.spec.tsthat directly simulates the race condition: callsreset(newValues)thenupdate(originalOpts)and asserts that values are not reverted - Existing test
form should reset default value when resetting in onSubmit(both core and react-form suites) continues to pass - All 499
@tanstack/form-coretests pass - All 123
@tanstack/react-formtests pass
Summary by CodeRabbit#
- Bug Fixes
- Fixed a race condition where resetting a form with new values could have those values unexpectedly reverted to stale defaults.
- 1
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/form-core/tests/FormApi.spec.ts (1)
147-173: ⚡ Quick winAdd one assertion path for
defaultStatechanges during the override cycle.Given the new one-cycle guard in
update(), it’s worth adding a companion case where staledefaultValuesare ignored but a realdefaultStatedelta still applies. That locks in the intended contract and prevents regressions around this race fix.🤖 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 147 - 173, Add an assertion path to the test that verifies legitimate defaultState changes are still applied during the update cycle. After the final update(originalOptions) call, add a scenario where you update the form with new defaultState values and assert that those changes are properly applied to form.state, ensuring that the guard preventing stale defaultValues from overwriting reset values does not inadvertently block valid defaultState updates. This locks in the contract that the one-cycle guard in the update() method only blocks stale defaultValues while still allowing real defaultState deltas to apply.🤖 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/src/FormApi.ts`: - Around line 1760-1773: The early return in the `_defaultValuesOverridden` block within the `update()` method prevents `shouldUpdateState` from being evaluated, which causes changes to `options.defaultState` to be dropped in that cycle. Instead of returning early after handling the defaultValues override, continue processing the update by allowing the `shouldUpdateState` evaluation to proceed. Merge the override logic so that the old defaultValues are preserved while still permitting synchronization of defaultState changes in the same cycle. --- Nitpick comments: In `@packages/form-core/tests/FormApi.spec.ts`: - Around line 147-173: Add an assertion path to the test that verifies legitimate defaultState changes are still applied during the update cycle. After the final update(originalOptions) call, add a scenario where you update the form with new defaultState values and assert that those changes are properly applied to form.state, ensuring that the guard preventing stale defaultValues from overwriting reset values does not inadvertently block valid defaultState updates. This locks in the contract that the one-cycle guard in the update() method only blocks stale defaultValues while still allowing real defaultState deltas to apply.🪄 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:
56b6b81d-b98f-4195-bf44-b4c411ddb596📥 Commits
Reviewing files that changed from the base of the PR and between 6a73479f2c2659550a6c8b456e3e139bf0d2142e and 39fb30bcf5497e28471dd70e51191ff88a6ee49c.
📒 Files selected for processing (2)
packages/form-core/src/FormApi.tspackages/form-core/tests/FormApi.spec.ts
@@ -1751,3 +1757,17 @@17511757 // Options need to be updated first so that when the store is updated, the state is correct for the derived state17521758 this.options = options175317591760+ // If reset(newValues) was called, the incoming `options` still carries the1761+ // original (pre-reset) defaultValues from the render closure. We must not1762+ // let those stale values overwrite what reset() set, so we skip the1763+ // shouldUpdateValues branch and clear the flag for the next render.1764+ if (this._defaultValuesOverridden) {1765+ this._defaultValuesOverridden = false1766+ // Keep the defaultValues that reset() stored on this.options so that1767+ // future renders compare against them correctly.1768+ this.options = {1769+ ...options,1770+ defaultValues: oldOptions.defaultValues,1771+ }1772+ return1773+ }⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Line 1764: early return unintentionally suppresses
defaultStatesynchronization.When
_defaultValuesOverriddenis set,update()returns before evaluatingshouldUpdateState, so a realoptions.defaultStatechange in that cycle can be silently dropped.💡 Suggested fix
- if (this._defaultValuesOverridden) { - this._defaultValuesOverridden = false - // Keep the defaultValues that reset() stored on this.options so that - // future renders compare against them correctly. - this.options = { - ...options, - defaultValues: oldOptions.defaultValues, - } - return - } + let nextOptions = options + if (this._defaultValuesOverridden) { + this._defaultValuesOverridden = false + // Keep defaultValues written by reset(), but still allow normal update() + // processing (eg defaultState sync) in this cycle. + nextOptions = { + ...options, + defaultValues: oldOptions.defaultValues, + } + this.options = nextOptions + } - const shouldUpdateValues = - options.defaultValues && - !evaluate(options.defaultValues, oldOptions.defaultValues) && + const shouldUpdateValues = + nextOptions.defaultValues && + !evaluate(nextOptions.defaultValues, oldOptions.defaultValues) && !this.state.isTouched const shouldUpdateState = - !evaluate(options.defaultState, oldOptions.defaultState) && + !evaluate(nextOptions.defaultState, oldOptions.defaultState) && !this.state.isTouched @@ - shouldUpdateState ? options.defaultState : {}, + shouldUpdateState ? nextOptions.defaultState : {}, shouldUpdateValues ? { - values: options.defaultValues, + values: nextOptions.defaultValues, } : {},🤖 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/src/FormApi.ts` around lines 1760 - 1773, The early return in the `_defaultValuesOverridden` block within the `update()` method prevents `shouldUpdateState` from being evaluated, which causes changes to `options.defaultState` to be dropped in that cycle. Instead of returning early after handling the defaultValues override, continue processing the update by allowing the `shouldUpdateState` evaluation to proceed. Merge the override logic so that the old defaultValues are preserved while still permitting synchronization of defaultState changes in the same cycle.The direction is right, but the one-shot flag reverts if
update()fires twice in a row with the same stale props before a genuinely new set arrives, which is a realistic case (a parent re-rendering for an unrelated reason re-runs the child's layout effect with the same props reference, or StrictMode double-invoking it).Reimplemented both this PR's logic and #2235's (which targets the same #1681, comparing against the previous update's props instead of a one-shot flag) side by side and ran the exact scenario, reset, then two consecutive
update()calls with unchanged stale props:[PR#2218 (flag)] after reset: { name: 'new-default' } [PR#2218 (flag)] after update #1 (stale): { name: 'new-default' } [PR#2218 (flag)] after update #2 (same stale props again): { name: 'original' } [PR#2218 (flag)] reset value survived double stale update: false [PR#2235 (tracking)] after reset: { name: 'new-default' } [PR#2235 (tracking)] after update #1 (stale): { name: 'new-default' } [PR#2235 (tracking)] after update #2 (same stale props again): { name: 'new-default' } [PR#2235 (tracking)] reset value survived double stale update: trueThe flag gets consumed by the first
update()call afterreset(), so by the second consecutive call with the same (unchanged) props,_defaultValuesOverriddenis alreadyfalseandupdate()falls through to the normalshouldUpdateValuescomparison, comparing the stale incoming props against thedefaultValuesthatreset()set, which reads as a real change and reverts.#2235 doesn't have this gap because it tracks what the previous update() call actually saw, not a one-shot signal, so a repeated identical
update()call keeps comparing against the same baseline instead of consuming a flag. It also doesn't need the earlyreturnthis PR adds (which skips the rest ofupdate(), includingshouldUpdateState, on the cycle it fires), since it folds the reset-preservation into the samethis.optionsassignment that runs either way.Since #2235 is already open against the same issue and (at least in this scenario) doesn't have the gap, might be worth comparing the two directly before merging either.
LeSingh1(GitHub profile, opens in a new tab) linked this to fix #1681
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
FormApigains a private_defaultValuesOverriddenboolean flag. Whenreset(values)is called with explicit values (andkeepDefaultValuesis not set), the flag is set totrue. On the nextupdate()call, the flag is detected, cleared, and the stale incomingoptions.defaultValuesis overwritten with the preserved post-reset defaults before returning early. A regression test covering the submit-then-reset-then-update race condition is added.Changes#
Reset/update race condition fix
_defaultValuesOverriddenflag,update()guard, andreset()setterpackages/form-core/src/FormApi.ts,packages/form-core/tests/FormApi.spec.ts_defaultValuesOverriddenboolean (defaultfalse).reset()sets it totruewhen new explicit values are applied.update()checks the flag, clears it, restores the preserveddefaultValuesfromoldOptions, and returns early — skipping the stale-options comparison. The regression test submits a form, resets it with{ name: 'test' }, callsupdate()with the original stale options, and asserts that neitherform.state.valuesnorform.options.defaultValuesreverts.Estimated code review effort#
🎯 2 (Simple) | ⏱️ ~10 minutes
Possibly related PRs#
FormApi.update()inpackages/form-core/src/FormApi.ts, specifically thedefaultValuescomparison and state update pathway, which overlaps directly with the guard added here.Suggested reviewers#
Poem#
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
#1681by fixing the race condition where reset(newValues) called in onSubmit was ignored due to stale options overwriting the new values.✨ 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