Skip to content

Commit

Permalink
subfields is empty also on undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
leoggonzalez committed Mar 27, 2022
1 parent 0f3769c commit ebe2e79
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 9 deletions.
9 changes: 5 additions & 4 deletions sandbox-app/nullable-field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@ interface Model {
avatar?: {
id: number;
url: string;
thumbs?: Record<number, string>;
} | null;
}

const initialValue: Model = {};

export function NullableField(): JSX.Element {
const { model, changes, fields, onSubmit, valid, dirty, submissionStatus } =
useForm({
model: initialValue,
useForm<Model>({
model: {
avatar: { id: 1, url: 'test', thumbs: { 10: 'test', 75: 'test' } },
},
onSubmit: async ({ model }) => {
// eslint-disable-next-line no-console
console.log(model);
Expand Down
8 changes: 4 additions & 4 deletions src/field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export interface Field<T> {

reset: () => void;
touch: () => void;
onChange: (value: T) => void;
onChange: (value: T | null) => void;
onBlur: () => void;
onFocus: () => void;
}
Expand Down Expand Up @@ -162,8 +162,8 @@ export class FieldImplementation<T, Model>
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)) {
Expand Down Expand Up @@ -212,7 +212,7 @@ export class FieldImplementation<T, Model>
}

private get subfields(): Array<FieldImplementation<unknown, Model>> {
if (this.value === null) return [];
if (this.value === null || this.value === undefined) return [];

return this.elements.concat(Object.values(this.#fields)) as Array<
FieldImplementation<unknown, Model>
Expand Down
13 changes: 12 additions & 1 deletion src/form.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) => {
Expand Down

0 comments on commit ebe2e79

Please sign in to comment.