From 70fa72bfafad70f16b69b055b546889d17395763 Mon Sep 17 00:00:00 2001 From: Erik Shestopal <6404663+erikshestopal@users.noreply.github.com> Date: Wed, 14 Aug 2019 15:39:49 -0700 Subject: [PATCH] fix: Use updater function in setState for Formbot updates (#58) --- src/Form/Formbot.js | 51 ++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/src/Form/Formbot.js b/src/Form/Formbot.js index 18b5e24..556f8df 100644 --- a/src/Form/Formbot.js +++ b/src/Form/Formbot.js @@ -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( @@ -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({ @@ -148,7 +146,8 @@ 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; }) @@ -156,7 +155,7 @@ export default class Formbot extends React.Component { this.updateField(field, { validated: true }).then(() => { this.setErrors({ [field]: errorMsg }, resolve); }); - }) + }); return; } @@ -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)); } ); };