0

I've reproduced the issue in the following codesandbox: https://codesandbox.io/s/unruffled-danilo-mbb0e?file=/src/App.js

I have a state array of objects [{name:"Tom"},{name:"Dick"},{name:"Harry"}]. I want to be able to duplicate the object present at a specific index in the array. I've provided a button "Duplicate" to do so in the sandbox.

Follow the following steps in the sandbox to recreate the issue:

  1. Click Duplicate under "Dick" to duplicate the Dick object in the state array
  2. Now click "change" under one of the two Dicks. Notice that my code only changes one "Dick" object in the state array, but the other duplicate one automatically gets changed.

I want to avoid this. I don't want the two Dick objects to remain linked forever. How do I do this?

1 Answers1

0

Your'e shallow copying the array. You need to deep copy. Replace let copy = cur.slice(); with let copy = cur.map(item => {return {...item}}); and your code should work. basically we need to destructure the inner object to get a new copy of the every object in the array. You can read about this here Object Immutability in JS