Skip to content

Commit

Permalink
fix: get FormField maybe undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
foreleven committed Aug 29, 2019
1 parent 0693624 commit df3c786
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 5 deletions.
3 changes: 2 additions & 1 deletion example/src/UserForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import * as React from 'react';
export const UserForm = () => {
const model = useStatedBean(UserModel);

console.log(model);
const { errors } = model.getFormField('user');

const handleSubmit = async e => {
const handleSubmit = async (e: React.MouseEvent) => {
e.preventDefault();
const valid = await model.validate('user');
if (valid) {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "stated-form-bean",
"version": "0.1.0-beta.5",
"version": "0.1.0-beta.6",
"description": "",
"main": "dist/cjs",
"module": "dist/es",
Expand Down
6 changes: 5 additions & 1 deletion src/core/FormField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class FormField<Values> {

constructor(
public readonly field: string | symbol,
private readonly _schema?: yup.Schema<Values>,
private _schema?: yup.Schema<Values>,
) {}

get errors() {
Expand Down Expand Up @@ -67,6 +67,10 @@ export class FormField<Values> {
};
}

setSchema(schema: yup.Schema<Values>) {
this._schema = schema;
}

_addError(error: yup.ValidationError) {
if (error.inner) {
if (error.inner.length === 0) {
Expand Down
14 changes: 12 additions & 2 deletions src/core/FormModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,21 @@ export class FormModel<Values> {
field: T,
schema: yup.Schema<Values[T]>,
): void {
this[fields][field] = new FormField(field as (string | symbol), schema);
const formField = this[fields][field];
if (formField !== undefined) {
formField.setSchema(schema);
} else {
this[fields][field] = new FormField(field as (string | symbol), schema);
}
}

getFormField<T extends keyof Values>(field: T): FormField<Values[T]> {
return this[fields][field];
const formField = this[fields][field];

if (formField === undefined) {
this[fields][field] = new FormField(field as (string | symbol));
}
return formField;
}

validate<T extends keyof Values>(
Expand Down

0 comments on commit df3c786

Please sign in to comment.