diff --git a/sandbox-app/nullable-field.tsx b/sandbox-app/nullable-field.tsx index 55c9ba5..3f80967 100644 --- a/sandbox-app/nullable-field.tsx +++ b/sandbox-app/nullable-field.tsx @@ -6,15 +6,16 @@ interface Model { avatar?: { id: number; url: string; + thumbs?: Record; } | null; } -const initialValue: Model = {}; - export function NullableField(): JSX.Element { const { model, changes, fields, onSubmit, valid, dirty, submissionStatus } = - useForm({ - model: initialValue, + useForm({ + model: { + avatar: { id: 1, url: 'test', thumbs: { 10: 'test', 75: 'test' } }, + }, onSubmit: async ({ model }) => { // eslint-disable-next-line no-console console.log(model); diff --git a/src/field.ts b/src/field.ts index 3a5b897..5ddf3e4 100644 --- a/src/field.ts +++ b/src/field.ts @@ -23,7 +23,7 @@ export interface Field { reset: () => void; touch: () => void; - onChange: (value: T) => void; + onChange: (value: T | null) => void; onBlur: () => void; onFocus: () => void; } @@ -162,8 +162,8 @@ export class FieldImplementation this.#onUpdate(); } - onChange = (value: T): void => { - this.value = value; + onChange = (value: T | null): void => { + this.value = value as T; if (value && typeof value === 'object') { if (Array.isArray(value)) { @@ -212,7 +212,7 @@ export class FieldImplementation } private get subfields(): Array> { - if (this.value === null) return []; + if (this.value === null || this.value === undefined) return []; return this.elements.concat(Object.values(this.#fields)) as Array< FieldImplementation diff --git a/src/form.spec.ts b/src/form.spec.ts index cdb352e..794220c 100644 --- a/src/form.spec.ts +++ b/src/form.spec.ts @@ -27,7 +27,7 @@ interface Model { name: string; age: number; description?: string; - nullableValue: string | null; + nullableValue: string | { id: string } | null; emails?: string[]; address?: { streetName?: string; @@ -352,6 +352,17 @@ describe(Form, () => { await form2.submit(); }); + it('can submit after updating to null value', async () => { + const form2 = createForm({ + value: { + nullableValue: { id: '1' }, + }, + }); + form2.fields.nullableValue.onChange(null); + expect(form2.fields.nullableValue.value).toBeNull(); + await form2.submit(); + }); + it('handles async functions', async () => { const form = createForm({ onSubmit: async (form) => {