Skip to content
This repository has been archived by the owner on Feb 16, 2021. It is now read-only.

Hold error message in state #390

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

Liooo
Copy link

@Liooo Liooo commented Jun 18, 2017

Currently we need to set up state by ourselves in order to set error message at runtime (e.g. when showing an error message from server API), as discussed in this issue #19.

I thought it'd be much simpler to have the error message in the components' state and then change the error message directly.

After the this change, this code can be written as below

var RegisterForm = React.createClass({
...
    onClick: function(evt) {
        evt.preventDefault();
        var values = this.refs.registerForm.getValue();
        if (values) {
            var errors = sendDataToServer(values);
            if (errors.email) {
              var emailComp = this.refs.registerForm.getComponent('email')
              emailComp.setState({ hasError: true, error: errors.email })
            }
        }
    },
...
    render: function() {
        var Form = t.form.createForm(Model, {
            fields: {
                email: {
                    type: 'email',
                    label: 'Email',
                }
            }
        });

@Liooo
Copy link
Author

Liooo commented Jun 18, 2017

Manipulating the child's state directly could be a bad practice, in which case we could expose an API like setError('error message') on the component

}

validate() {
const result = t.validate(this.getValue(), this.props.type, this.getValidationOptions())
this.setState({ hasError: !result.isValid() })
this.setState({ hasError: !result.isValid(), error: this.getError() })

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be a problem. e.g. if there is an error hasError will become true but in the moment when this.getError() is called hasError is still true. The result is that component will have error style but there is no error message. Possible solution is to wait until state has changed and than set state for error or, pass to getError param true to ignore the hasError state.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's right, thanks.

@gcanti
any opinions regarding this PR?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants