0

I am a newbie in React. I need some help to solve this issue

Code:

 this.state={
    testState: {
        testArray: [
            { name: "bob" },
            { name: "alice" },
            { name: "john" }
        ]
    }
}

testFn = () => {

        let a;
        a = { ...this.state.testState }; //using spread operator to copy the object instead of referencing
        a.testArray.map((obj) => {
            obj.name = "React is awesome"
        })
        console.log(this.state.testState)
    }

Output:

testArray: Array(3)
0: {name: "React is awesome"}
1: {name: "React is awesome"}
2: {name: "React is awesome"}

I have to modify a without altering the state. But here, the state is also changed along with the iteration. How can I solve this problem?

Dan O
  • 6,022
  • 2
  • 32
  • 50
Muhzin
  • 390
  • 6
  • 19
  • 1
    unrelated to the issue, but you're also using `.map()` for simple iteration and not using its return value. For simple iteration, you can use `.forEach` which is built for that sort of thing – Nick Parsons Mar 09 '20 at 11:07

1 Answers1

1

The spread operator only does a shallow copy

To guarantee a full object copy use

const copiedState = JSON.parse(JSON.stringify(yourState))

Better solution

Sove it at the source. Don't make deep state, its actually a key part of writing objects in the state. You should keep them very shallow. In this case you are already way deep with Obj -> Array -> Obj.

Joe Lloyd
  • 19,471
  • 7
  • 53
  • 81