Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(field): remove fields from the form when unmounted #233

Merged
merged 1 commit into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading