1

I'm writing reactjs and I want to use The Power Of Not Mutating Data. In code below this.state.messages['hydra:member'] is an array of objects and I want to know that in this code messages is a reference to this.state.messages['hydra:member'] or a new array. If I mutate it this.state.messages['hydra:member'] will change or not?

let {'hydra:member': messages = []} = this.state.messages;

and what about this:

if(this.state.messages['hydra:member'] !== undefined) {
    let messages = this.state.messages['hydra:member'];
}

1 Answers1

0

To create a deep copy of this.state.messages['hydra:member'] you can do as follows

if(this.state.messages['hydra:member'] !== undefined) {
    let messages = JSON.parse(JSON.stringify(this.state.messages['hydra:member']));
   //use messages here
}

Now, when you use the messages array you will not be mutating the state.

palsrealm
  • 5,083
  • 1
  • 20
  • 25
  • I know this but I want to know that can I do this with "Assignment Destructuring"? – Mohammad Zare Moghadam Oct 03 '17 at 13:02
  • That's a pretty expensive way of doing a deep copy. – Ouroborus Oct 03 '17 at 15:56
  • @Ouroborus I am going by https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/5344074#5344074 Discaimer: I have not personally tested the efficiency of the solution with compared to others. – palsrealm Oct 03 '17 at 17:02