11

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?

4
  • 1
    Shallow copy with .slice() Commented Jul 20, 2018 at 14:35
  • The mentioned copy array duplicate answer is just copying array in plain js. React best practice is NOT to mutate the state. @JonasWilms Commented Oct 4, 2019 at 18:20
  • @fabricioG "just copying array" is "NOT mutating the state" ? Commented Oct 4, 2019 at 18:34
  • In the example the question has he is specifically referencing the main stage changes. That's why I'm saying isn't that encouraging mutation of the original state? Commented Oct 4, 2019 at 18:39

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

8 Comments

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
You should add more code.
`` 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
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.
@mahdi - add whatever seems relevant to the question, to the question. In addition, please explain why you are doing it at all.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.