Skip to content

Commit

Permalink
empty subfield when value is null
Browse files Browse the repository at this point in the history
  • Loading branch information
leoggonzalez committed Mar 27, 2022
1 parent fa51b49 commit 0f3769c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 18 deletions.
32 changes: 14 additions & 18 deletions sandbox-app/nullable-field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,42 @@ import { Input } from './components/Input';

interface Model {
avatar?: {
id: number;
url: string;
} | null;
}

const initialValue: Model = {};

export function NullableField(): JSX.Element {
const {
model,
changes,
fields,
onSubmit,
valid,
dirty,
submissionStatus,
reset,
} = useForm({
model: initialValue,
onSubmit: async ({ model }) => {
// eslint-disable-next-line no-console
console.log(model);
},
});
const { model, changes, fields, onSubmit, valid, dirty, submissionStatus } =
useForm({
model: initialValue,
onSubmit: async ({ model }) => {
// eslint-disable-next-line no-console
console.log(model);
},
});

return (
<>
<h2 id="nullable-field">Nullable Field</h2>
<form onSubmit={onSubmit}>
{model.avatar !== null ? (
{Object.keys(model.avatar || {}).length ? (
<>
<Input {...fields.avatar.fields.url} />
<button onClick={() => fields.avatar.onChange(null)} type="button">
remove avatar
</button>
</>
) : (
<button onClick={() => fields.avatar.fields.url.onChange('')}>
<button onClick={() => fields.avatar.onChange({ id: 1, url: '' })}>
add avatar
</button>
)}
<footer style={{ marginTop: 16 }}>
<button>Submit</button>
</footer>
</form>
<h4>Model</h4>
<pre>
Expand Down
3 changes: 3 additions & 0 deletions src/field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ export class FieldImplementation<T, Model>

onChange = (value: T): void => {
this.value = value;

if (value && typeof value === 'object') {
if (Array.isArray(value)) {
this.#resetArray();
Expand Down Expand Up @@ -211,6 +212,8 @@ export class FieldImplementation<T, Model>
}

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

return this.elements.concat(Object.values(this.#fields)) as Array<
FieldImplementation<unknown, Model>
>;
Expand Down

0 comments on commit 0f3769c

Please sign in to comment.