0

I want to make a "hard copy" of the object that is assigned to this.state and change the copy in the sayHello method. When I use Object.assign it changes this.state. How can I fix this? Or......can I ? ~~~~~~

class App {
    constructor() {
        this.state = {
            items: []
        }

    }

    sayHello() {

        //______I want to clone this.state so I can modify the copy____
        //______I use Object.assign()__________________________________

        let objCopy = Object.assign({}, this.state)

        //_____I change the copy_______________________________________
        objCopy.items.push({ text: "hi there" })

        //_____But the original was changed...nooooooooo!______________

        console.log(this.state);  // Changed!  { items: [ { text: 'hi there' } ] }


    }

}

let myApp = new App()

myApp.sayHello();
jack
  • 11
  • 2
  • You're wrong. It's a different question – jack Apr 14 '18 at 09:33
  • No, it's the same. Object.assign [doesn't do](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Deep_Clone) deep cloning so you have to go different way – skyboyer Apr 14 '18 at 09:36
  • `Object.assign` only creates a copy of a reference to `items`. The underlying array stays the same, so it's natural you're modifying it -- you're accessing the same array, but from a different refrence. What you can try to do is to shallow copy the `items` as well -- `objCopy.items = [...this.state.items]` –  Apr 14 '18 at 09:37

0 Answers0