I need to copy an object from this.state
to change some of its property values.
For example in the following method state is being mutated directly (this.state.errors = {}
)
authorFormIsValid = () => {
var formIsValid = true;
this.state.errors = {}; //clear any previous 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) The object spread operator
let errors={...this.state.errors};
b) Or Object.assign
let errors=Object.assign({},this.state.errors);
But sometimes I've seem some examples in which object destructuring
it is used like this:
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 object destructuring
equivalent to the other two methods mentioned above? I mean, will I avoid mutating the state directly by using simple object destructuring
?
Object destructuring
works by reference
and hence you should not be mutating the object after destructuring it. So the practice of
let {errors, author} = this.state;
errors = {}; //clear any previous errors.
is actually wrong.
See a snippet of reference call below
let obj = {
foo: {
bar: 1
}
}
let { foo } = obj;
console.log(foo.bar); // 1
console.log(obj.foo.bar); // 1
foo.bar++;
console.log(foo.bar); // 2
console.log(obj.foo.bar); // 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With