Skip to content

Commit

Permalink
fix: remove fields from the form when unmounted
Browse files Browse the repository at this point in the history
  • Loading branch information
Cysword authored and myparcel-bot[bot] committed Jan 25, 2024
1 parent f746a9a commit 6bd45bd
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
34 changes: 34 additions & 0 deletions libs/core/src/utils/createField.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,5 +93,39 @@ describe('createField', () => {
expect(wrapper.html()).toMatchSnapshot();
expect((await wrapper.findByRole<HTMLInputElement>('textbox')).value).toBe('value2');
});

it('should remove the field from the form when unmounted', async () => {
expect.assertions(2);

const form = createForm('renderModular', {});
const field = createField({
name: 'modularTest',
label: 'fieldLabel',
ref: ref('value2'),
component: testComponent,
});

const wrapper = render(form.Component, {
slots: {
default: () => h('div', [h(field.Component), h(field.Label), h(field.Errors)]),
},
});

await flushPromises();

expect(form.instance.fields.value).toHaveLength(1);

await wrapper.unmount();

const wrapper2 = render(form.Component, {
slots: {
default: () => h('div', [h(field.Component), h(field.Label), h(field.Errors)]),
},
});

await flushPromises();

expect(form.instance.fields.value).toHaveLength(1);
});
});
});
8 changes: 8 additions & 0 deletions libs/core/src/utils/createField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
h,
markRaw,
onMounted,
onUnmounted,
type Ref,
ref,
reactive,
Expand Down Expand Up @@ -37,6 +38,13 @@ const createMainComponent = <Type = unknown, Props extends ComponentProps = Comp
element.value = await form.addElement(field);
});

onUnmounted(() => {
if (element.value) {
form.removeElement(element.value.name);
element.value = undefined;
}
});

return {
element,
form,
Expand Down

0 comments on commit 6bd45bd

Please sign in to comment.