Skip to content

Commit

Permalink
fix: form should now be aware of field unmounting
Browse files Browse the repository at this point in the history
* Add basic tests for arrays

* Ran prettier

* Ran prettier

* Add new test for bug

* Fix bug regarding preserved values even if field is umounted

* Run prettier

* Update store subscription when removingFields
  • Loading branch information
Christian24 authored Nov 5, 2023
1 parent fd19453 commit f75aab2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
7 changes: 5 additions & 2 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,11 @@ export class FormApi<TFormData, ValidatorType> {
}

deleteField = <TField extends DeepKeys<TFormData>>(field: TField) => {
delete this.state.values[field as keyof TFormData]
delete this.state.fieldMeta[field]
const newState = { ...this.state }
delete newState.values[field as keyof TFormData]
delete newState.fieldMeta[field]

this.store.setState((_) => newState)
}

pushFieldValue = <TField extends DeepKeys<TFormData>>(
Expand Down
8 changes: 7 additions & 1 deletion packages/form-core/src/tests/FieldApi.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { expect } from 'vitest'
import { expect, vitest } from 'vitest'

import { FormApi } from '../FormApi'
import { FieldApi } from '../FieldApi'
Expand Down Expand Up @@ -597,11 +597,17 @@ describe('field api', () => {
})

const unmount = field.mount()
const callback = vitest.fn()
const subscription = form.store.subscribe(callback)
unmount()
const info = form.getFieldInfo(field.name)
subscription()
expect(info.instances[field.uid]).toBeUndefined()
expect(Object.keys(info.instances).length).toBe(0)

// Check that form store has been updated
expect(callback).toHaveBeenCalledOnce()

// Field should have been removed from the form as well
expect(form.state.values.name).toBeUndefined()
expect(form.state.fieldMeta.name).toBeUndefined()
Expand Down

0 comments on commit f75aab2

Please sign in to comment.