Skip to content

Commit

Permalink
fix(form): fix form.setValue not working due to unwrapped refs
Browse files Browse the repository at this point in the history
  • Loading branch information
EdieLemoine committed Jan 10, 2024
1 parent 88b7af3 commit 58824dc
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions libs/core/src/form/Form.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -34,6 +34,12 @@ export class Form<V extends FormValues = FormValues> {
public readonly stable: FormInstance<V>['stable'] = ref(false);
public readonly values: FormInstance<V>['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<V>['name'], formConfig: ToRecord<InstanceFormConfiguration<V> & FormHooks>) {
const {fields, ...config} = formConfig;

Expand Down Expand Up @@ -97,7 +103,7 @@ export class Form<V extends FormValues = FormValues> {
}

public getField<F extends AnyElementInstance | null = AnyElementInstance | null>(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<T = unknown>(fieldName: string): T {
Expand All @@ -114,6 +120,7 @@ export class Form<V extends FormValues = FormValues> {
const index = get(this.fields).findIndex((field) => field.name === name);

get(this.fields).splice(index, 1);
this.getFieldMemoized.delete(name);
}

public async reset(): Promise<void> {
Expand Down Expand Up @@ -225,6 +232,7 @@ export class Form<V extends FormValues = FormValues> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
this.model[name] = instance;
this.getFieldMemoized.delete(name);

return instance;
}
Expand Down

0 comments on commit 58824dc

Please sign in to comment.