Reputation: 35
I'm validating a login form and dynamically displaying errors, passed as props from the child component. When I set my errors object using Object.assign, the errorText does not appear below the field. If I use setState(), the errorText will display, but the errors object in state does not get updated with all the errors. I believe this has to do with the async nature of setState().
login_page.js (parent component)
constructor(props) {
super(props);
this.state = {
login: {
userName: "",
password: ""
},
errors: {}
};
}
loginFormIsValid() {
var formIsValid = true;
this.setState({
errors: {}
});
if (this.state.login.password === "") {
Object.assign(this.state, {
errors: Object.assign(this.state.errors, {password: "Password is required"})
});
formIsValid = false;
}
if (this.state.login.userName === "") {
Object.assign(this.state, {
errors: Object.assign(this.state.errors, {userName: "Username is required"})
});
formIsValid = false;
}
return formIsValid;
}
login_form.js (child component)
<form
<TextField
name="userName"
errorText={this.props.errors.userName} />
<br />
<TextField
name="password"
errorText={this.props.errors.password} />
<br />
<RaisedButton
label="Log in"
type="submit" />
</form>
I am a React / Material-UI newb so any help is appreciated.
Upvotes: 0
Views: 2790
Reputation: 3171
Use setState to change states (not Object.assign). So when you are updating state. Also, the usage for Object.assign is
Object.assign(newObject, ...objectsToCopyFrom)
which will look like
var newErrors = Object.assign(this.state.errors, {password: "Password is required"});
Then use setState to set the new properties, just replacing what has changed.
this.setState({ errors: newErrors });
Upvotes: 1