10

When I want to copy the state like this:

let copy = this.state.foo
copy.push('bar')

the state copied correctly, but with its reference, and when I change 'copy' the main state changes.

What should I do to avoid this change?

peterh
  • 11,875
  • 18
  • 85
  • 108
Mahdi
  • 1,355
  • 1
  • 12
  • 28

1 Answers1

12

You can use array spread or Array.concat() to make a shallow clone, and add new items as well):

const state = {
  foo: ['bar']
};

const copy = [...state.foo, 'bar'];

console.log(copy === state.foo); // false
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Oh, man, My problem did not solve let me specify more I have a state that named bar and I have a function named addBar and this function add the last item of the bar to the bar but I want to copy it without reference I do what you said but it didn't work for me – Mahdi Jul 20 '18 at 17:28
  • You should add more code. – Ori Drori Jul 20 '18 at 18:09
  • `` addBar = () => { let bar = [...this.state.bars,{...this.state.bars[this.state.bars.length - 1]}] this.setState({ bars:bar }) } `` this code must add the last item of the bar to the bar but it doesn't work – Mahdi Jul 20 '18 at 18:51
  • In the question would be nicer. – Ori Drori Jul 20 '18 at 19:16
  • Is there any way for me to send the whole code for you ?? – Mahdi Jul 20 '18 at 19:26
  • 1
    It seems like you clone the state.bars, and the last items of bars. And then without changing anything, you set it back to the state. Since you don't change anything, What are you trying to achieve? In addition, you should use setState with an updater function. – Ori Drori Jul 20 '18 at 19:26
  • 1
    @mahdi - add whatever seems relevant to the question, to the question. In addition, please explain why you are doing it at all. – Ori Drori Jul 20 '18 at 19:27
  • For futur visitor, I found the correct answer here https://stackoverflow.com/questions/7486085/copy-array-by-value You'll need to understand your need with shallow vs deep copy. – Yannick Lescure Sep 23 '22 at 14:24