fix: bump array version on reset so array fields re-render #2243
main fromrefs/pull/2243/head·opened Summary#
- Bump
_arrayVersionafterform.reset()andform.resetField()when the target field is an array. - Fix React array fields not re-rendering when a reset shortens the array (e.g.
[1,2,3]→[4]previously still rendered 3 items). - Fixes #2228.
Test Plan#
pnpm run test:libinpackages/form-corepnpm run test:libinpackages/react-form
Summary by CodeRabbit#
- Bug Fixes
- Fixed array-based form fields not re-rendering correctly after resetting the form or an individual field.
- Array fields now immediately reflect changes in length and updated values after a reset.
- 1
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/form-core/src/FormApi.ts (1)
1850-1858: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract duplicated array-version-bump loop into a shared helper.
The loop at lines 1851–1858 is identical to the one already in
update()at lines 1786–1793. Extracting it into a private method (e.g.,bumpArrayVersionsForAllFields()) would eliminate the duplication and ensure both call sites stay in sync.♻️ Proposed refactor
+ /** + * `@private` Bump _arrayVersion for every mounted field whose value is an array. + */ + private bumpArrayVersionsForAllFields = () => { + const helper = metaHelper(this) + for (const fieldKey of Object.keys( + this.fieldInfo, + ) as DeepKeys<TFormData>[]) { + if (Array.isArray(this.getFieldValue(fieldKey))) { + helper.bumpArrayVersion(fieldKey) + } + } + } + reset = (values?: TFormData, opts?: { keepDefaultValues?: boolean }) => { // ... existing reset logic ... - const helper = metaHelper(this) - for (const fieldKey of Object.keys( - this.fieldInfo, - ) as DeepKeys<TFormData>[]) { - if (Array.isArray(this.getFieldValue(fieldKey))) { - helper.bumpArrayVersion(fieldKey) - } - } + this.bumpArrayVersionsForAllFields() }Then apply the same replacement in
update()at lines 1786–1793.🤖 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 1850 - 1858, Extract the duplicated array-version-bump loop from update() and the shown flow into a shared private method, such as bumpArrayVersionsForAllFields(). Have the helper create or use metaHelper(this), iterate over fieldInfo keys, and call bumpArrayVersion for array-valued fields; replace both existing loops with calls to this method.🤖 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 2966-2969: Add a FormApi.spec.ts test covering resetField on an array field, using the existing FormApi, FieldApi, and resetField test patterns. Set an array value, call resetField, then assert the default array is restored and the field meta _arrayVersion is bumped as expected. --- Nitpick comments: In `@packages/form-core/src/FormApi.ts`: - Around line 1850-1858: Extract the duplicated array-version-bump loop from update() and the shown flow into a shared private method, such as bumpArrayVersionsForAllFields(). Have the helper create or use metaHelper(this), iterate over fieldInfo keys, and call bumpArrayVersion for array-valued fields; replace both existing loops with calls to this method.🪄 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:
b94af9cf-baaa-470c-9593-93e75079298b📥 Commits
Reviewing files that changed from the base of the PR and between 5d1128141a705ebb24ade1275b3117bb4c8b1bdc and b59f247d895751a125f828b4f215d4d7be59e2c8.
📒 Files selected for processing (4)
.changeset/fix-array-reset-rerender.mdpackages/form-core/src/FormApi.tspackages/form-core/tests/FormApi.spec.tspackages/react-form/tests/useField.test.tsx
packages/form-core/src/FormApi.ts lines 2966 to 2969@@ -2954,3 +2963,7 @@29542963 : prev.values,29552964 }29562965 })2966+2967+ if (Array.isArray(this.getFieldValue(field))) {2968+ metaHelper(this).bumpArrayVersion(field)2969+ }🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Add test coverage for
resetFieldarray version bump.The
reset()path has a dedicated test inFormApi.spec.ts, but theresetField()array-version bump (lines 2967–2968) has no corresponding test. A regression could silently break this path.🧪 Suggested test
it('should bump array version when resetField is called on an array field', () => { const form = new FormApi({ defaultValues: { items: [1, 2, 3], }, }) form.mount() const field = new FieldApi({ form, name: 'items' }) field.mount() form.setFieldValue('items', [1, 2, 3, 4, 5]) // _arrayVersion is bumped by pushFieldValue or setFieldValue paths form.resetField('items') expect(form.getFieldValue('items')).toEqual([1, 2, 3]) expect(form.getFieldMeta('items')?._arrayVersion).toBe(1) })🤖 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 2966 - 2969, Add a FormApi.spec.ts test covering resetField on an array field, using the existing FormApi, FieldApi, and resetField test patterns. Set an array value, call resetField, then assert the default array is restored and the field meta _arrayVersion is bumped as expected.Went to check why bumping
_arrayVersionspecifically is what's needed here, and it's becausereact-form'suseFielddeliberately subscribes tostate.meta._arrayVersioninstead ofstate.valueformode="array"fields, there's already a comment there referencing #1925 explaining it's an intentional optimization to avoid re-rendering on every child property change. That means for an array field, React genuinely does not know the array changed unless_arrayVersionitself changes, no matter what happened to the actual array reference or length.form.reset()/resetField()changing the array without touching that counter is exactly the kind of thing that selector is blind to, so the fix is targeting the right mechanism, not just papering over a symptom.Checked the ordering in both call sites too. In
reset(), the new loop runs after thebaseStore.setStatethat actually commits the new values, sothis.getFieldValue(fieldKey)inside the loop is reading the post-reset array, not stale state. Same story inresetField.One minor thing, not a correctness issue:
resetFieldisn't wrapped inbatch(), so settingfieldMetaBase[field]todefaultFieldMeta(which resets_arrayVersionto0) and then callingbumpArrayVersionright after are two separate store commits rather than one. Since the array value itself is already correct as of the first commit, this shouldn't produce wrong output, just possibly one extra render pass in cases where_arrayVersionwasn't already0going in. Worth a look if this file already batches similar multi-step meta+value updates elsewhere, but not something I'd block on.Good that the React test renders through an actual
mode="array"field and checks the DOM list length after reset, rather than asserting on internal state, since the whole point of the fix is what the UI shows, not just what the store holds.hemraj-007(GitHub profile, opens in a new tab) linked this to fix #2228
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
Form reset operations now bump
_arrayVersionfor array fields, ensuring array-mode adapters re-render when reset values change array length. Core and React tests cover form resets to shorter arrays, and a changeset records patch releases.Changes#
Array reset rerender
packages/form-core/src/FormApi.ts,.changeset/fix-array-reset-rerender.mdreset()andresetField()bump array metadata versions after applying array values; release metadata records the fix and patch releases.packages/form-core/tests/FormApi.spec.ts,packages/react-form/tests/useField.test.tsx_arrayVersion, field values, and rendered list entries.Estimated code review effort: 2 (Simple) | ~10 minutes
Possibly related PRs
_arrayVersionmechanism for array swap and move behavior.Suggested reviewers:
crutchcorn🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
#2228and backed by tests.✨ 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