Skip to content

fix(forms): cleanup dynamically removed form fields#8572

Open
Trandx wants to merge 1 commit into
primefaces:masterfrom
Trandx:fix/forms-dynamic-field-cleanup
Open

fix(forms): cleanup dynamically removed form fields#8572
Trandx wants to merge 1 commit into
primefaces:masterfrom
Trandx:fix/forms-dynamic-field-cleanup

Conversation

@Trandx
Copy link
Copy Markdown

@Trandx Trandx commented May 13, 2026

Fix dynamic field cleanup in forms

Related issue: #8408

Problem

When dynamically removing form fields using v-if, v-for, or custom dynamic arrays, the field state was not properly cleaned up from the internal form store.

Although the component was destroyed, the following data remained registered internally:

  • field state (_states)
  • validation errors
  • dirty/touched flags
  • field watchers

This caused several issues:

  • stale validation errors
  • invalid form state after field removal
  • orphan reactive watchers
  • memory leaks
  • removed fields still appearing in submit state

Example

<MyField v-if="visible" name="email" />

When visible becomes false, the component is unmounted visually, but the internal form state still contains:

_states.email

As a result:

  • the form may still be invalid
  • validation errors may still exist
  • watchers continue reacting to changes

The same issue also affects dynamic arrays:

<MyField
  v-for="(item, index) in items"
  :key="item.id"
  :name="`contacts.${index}.email`"
/>

Removing an item from the array leaves stale field states and watchers behind.


Root Cause

defineField() registers field state and watchers internally, but there was no cleanup mechanism when a field component was unmounted.

As a result, dynamically removed fields remained inside:

fields
_states

Solution

This PR introduces a new unregister(field) cleanup method in useForm.

The method now:

  • stops the field watcher
  • removes the field definition
  • clears the internal field state

Field components automatically call unregister() during beforeUnmount.


Result

Dynamic form fields are now properly cleaned up when removed.

This fixes:

  • stale validation states
  • lingering errors
  • orphan watchers
  • invalid form validity after field removal

and significantly improves dynamic form reliability.


Test Reproduction

https://stackblitz.com/edit/vitejs-vite-pub96hsp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant