From bf2d9c59adeede43529c9dc946c4cdb8070839d5 Mon Sep 17 00:00:00 2001 From: Edie Lemoine Date: Wed, 10 Jan 2024 17:57:01 +0100 Subject: [PATCH] fix(form): fix setValue not working occasionally (#228) removes usage of `this.model` internally as it causes refs to be unwrapped _sometimes_. --- libs/core/src/form/Form.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/libs/core/src/form/Form.ts b/libs/core/src/form/Form.ts index 4c1951d3..ebb640f0 100644 --- a/libs/core/src/form/Form.ts +++ b/libs/core/src/form/Form.ts @@ -1,10 +1,10 @@ import {computed, ref, watch, reactive, unref} from 'vue'; -import {get, isDefined} from '@vueuse/core'; +import {get, isDefined, useMemoize} from '@vueuse/core'; import {createHookManager} from '@myparcel-vfb/hook-manager'; import {isOfType} from '@myparcel/ts-utils'; import {markComponentAsRaw} from '../utils'; -import {type ToRecord} from '../types/common.types'; import { + type ToRecord, type AnyElementConfiguration, type AnyElementInstance, type ElementName, @@ -34,6 +34,12 @@ export class Form { public readonly stable: FormInstance['stable'] = ref(false); public readonly values: FormInstance['values']; + private getFieldMemoized = useMemoize((name: string): AnyElementInstance | null => { + const found = get(this.fields).find((field) => field.name === name); + + return found ?? null; + }); + public constructor(name: FormInstance['name'], formConfig: ToRecord & FormHooks>) { const {fields, ...config} = formConfig; @@ -97,7 +103,7 @@ export class Form { } public getField(name: string): F { - return (this.model[name] ?? get(this.fields).find((field) => field.name === name) ?? null) as F; + return this.getFieldMemoized(name) as F; } public getValue(fieldName: string): T { @@ -114,6 +120,7 @@ export class Form { const index = get(this.fields).findIndex((field) => field.name === name); get(this.fields).splice(index, 1); + this.getFieldMemoized.delete(name); } public async reset(): Promise { @@ -225,6 +232,7 @@ export class Form { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error this.model[name] = instance; + this.getFieldMemoized.delete(name); return instance; }