Skip to content
This repository has been archived by the owner on Oct 6, 2020. It is now read-only.

Commit

Permalink
fix: Use updater function in setState for Formbot updates (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
erikshestopal authored Aug 14, 2019
1 parent 68df3a2 commit 70fa72b
Showing 1 changed file with 25 additions and 26 deletions.
51 changes: 25 additions & 26 deletions src/Form/Formbot.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,18 @@ export default class Formbot extends React.Component {
}));
}

setValues(values = {}) {
this.setState(
{
values: {
...this.state.values,
...values,
},
},
this.validateAllFields
);
}
setValues = (values = {}) =>
new Promise(resolve => {
this.setState(
state => ({
values: {
...state.values,
...values,
},
}),
() => this.validateAllFields().then(resolve)
);
});

setErrors = (errors = {}, cb) =>
this.setState(
Expand All @@ -97,24 +98,21 @@ export default class Formbot extends React.Component {
cb
);

updateField(field, updates = {}) {
return new Promise(resolve => {
const fieldState = this.state.fields[field] || {};

updateField = (field, updates = {}) =>
new Promise(resolve => {
this.setState(
{
state => ({
fields: {
...this.state.fields,
...state.fields,
[field]: {
...fieldState,
...state.fields[field],
...updates,
},
},
},
}),
resolve
);
});
}

reset = () => {
this.setState({
Expand Down Expand Up @@ -148,15 +146,16 @@ export default class Formbot extends React.Component {
let errorMsg;

if (hasSchema && typeof validation.validate === 'function') {
validation.validate(fieldValue, validationOpts)
validation
.validate(fieldValue, validationOpts)
.catch(e => {
errorMsg = e.message;
})
.finally(() => {
this.updateField(field, { validated: true }).then(() => {
this.setErrors({ [field]: errorMsg }, resolve);
});
})
});

return;
}
Expand Down Expand Up @@ -201,16 +200,16 @@ export default class Formbot extends React.Component {

onChange = (field, value) => {
this.setState(
{
state => ({
values: {
...this.state.values,
...state.values,
[field]: value,
},
},
}),
() => {
this.updateField(field, { validated: false })
.then(() => this.validateField(field))
.then(() => this.props.onChange(field, value, this.state.values))
.then(() => this.props.onChange(field, value, this.state.values));
}
);
};
Expand Down

0 comments on commit 70fa72b

Please sign in to comment.