Stefan Stefan - 1 month ago 9
React JSX Question

ReactJS recieving form errors from server

Below is my signup function in React. How can I render the errors it recieves from backend ? I tried to put a this.setResponse into the catch part ... that didn't work. I understand that componentWillReceiveProps should handle updates but this is an update from a Service (also below) not from a parent component.

If I print the err I can see a dictionary with errors, but I don't see how to pass them to the form or to the fields for rendering.

signup(evt) {
evt.preventDefault();
...
Auth.signup(dict)
.catch(function(err) {
alert("There's an error signing up");
console.log(err.response);
});
},


The Auth service is defined like this:

signup(dict) {
console.log(dict);
return this.handleAuth(when(request({
url: UserConstants.SIGNUP_URL,
method: 'POST',
type: 'json',
data: dict
})));
}


And I hoped to send errors to the fields with the following:

<UserNameField
ref="username"
responseErrors={this.responseErrors}
/>

Answer

Presuming that UserNameField is in the same component as the auth callback you can just set the state which will trigger a re-render and pass the values through UserNameField as props.

signup(evt) {
    evt.preventDefault();
    ...
      Auth.signup(dict)
        .catch((err) => {
            alert("There's an error signing up");
            console.log(err.response);
            this.setState({error: err});
      });
},

<UserNameField
    ref="username"
    responseErrors={this.responseErrors}
    error={this.state.error}
/>

This is the same as .bind(this).