gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

Hold error message in state #390

Open Liooo opened 7 years ago

Liooo commented 7 years ago

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 commented 7 years ago

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