I need to copy an object from this.stateto change some of its property values.
For example, in the following method, the state is mutated directly ( this.state.errors = {})
authorFormIsValid = () => {
var formIsValid = true;
this.state.errors = {};
if (this.state.author.firstName.length < 3) {
this.state.errors.firstName = 'First name must be at least 3 characters.';
formIsValid = false;
}
if (this.state.author.lastName.length < 3) {
this.state.errors.lastName = 'Last name must be at least 3 characters.';
formIsValid = false;
}
this.setState({errors: this.state.errors});
return formIsValid;
};
To avoid this, I know that we can use:
a) object distribution operator
let errors={...this.state.errors};
b) Or Object.assign
let errors=Object.assign({},this.state.errors);
But sometimes it seems to me a few examples in which object destructuringit is used as follows:
authorFormIsValid = () => {
let formIsValid = true;
//Destructuring error and authors from this.state
let {errors, author} = this.state;
errors = {}; //clear any previous errors.
if (author.firstName.length < 3) {
errors.firstName = 'First name must be at least 3 characters.';
formIsValid = false;
}
if (author.lastName.length < 3) {
errors.lastName = 'Last name must be at least 3 characters.';
formIsValid = false;
}
this.setState({errors});
return formIsValid;
};
So my question is: is it equivalent to the object destructuringother two methods mentioned above? I mean, can I avoid mutating the state directly using simple object destructuring?