1

I have users and selectedUser as useState.

let users=[{"firstName":"John", "lastName":"Doe"},
  {"firstName":"Anna", "lastName":"Smith"},
  {"firstName":"Peter", "lastName":"Jones"}];

const [selectedUser, setselectedUser] = useState(undefined);

setselectedUser(users[0]);

var a = selectedUser;
a.firstName = "XYZ"
setselectedUser(a);

The above code changes the value of users to

[{"firstName":"XYZ", "lastName":"Doe"},
      {"firstName":"Anna", "lastName":"Smith"},
      {"firstName":"Peter", "lastName":"Jones"}];

How can I prevent any changes to users when I change selectedUser?

Archit Sandesara
  • 605
  • 1
  • 12
  • 25

1 Answers1

3

To clone an object you can use the spread syntax {...x}.

let users=[{"firstName":"John", "lastName":"Doe"},
  {"firstName":"Anna", "lastName":"Smith"},
  {"firstName":"Peter", "lastName":"Jones"}];

const newThing = {...users[0]}; // we clone the object
newThing.firstName = 'New name'

console.log(newThing, users);
// ^-- newThing has the new firstName but users remains untouched

So your example code would look like this:

let users=[{"firstName":"John", "lastName":"Doe"},
  {"firstName":"Anna", "lastName":"Smith"},
  {"firstName":"Peter", "lastName":"Jones"}];

const [selectedUser, setselectedUser] = useState(undefined);

setselectedUser({...users[0]}); // <-- I changed this

var a = selectedUser;
a.firstName = "XYZ"
setselectedUser(a);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Dominik
  • 6,078
  • 8
  • 37
  • 61
  • Just a heads up, you probably want to use an Object spread in this instance opposed to the array spread, otherwise this looks good – Ibz Dec 02 '20 at 21:09
  • 1
    Yeah just fixed that ;) – Dominik Dec 02 '20 at 21:09
  • This solution should work in this particular case, but extra caution is needed if the object to clone has nested objects. – Mackers Dec 02 '20 at 21:16
  • Thanks for the answer Dominik. @Mackers The solution doesn't work if the user object is nested. What's the correct way in this scenario? – Archit Sandesara Dec 03 '20 at 04:10
  • Indeed @ArchitSandesara. That was not in your question ;) There are a bunch of solutions already out there to may help you: https://stackoverflow.com/questions/6089058/nodejs-how-to-clone-an-object – Dominik Dec 03 '20 at 04:13
  • https://stackoverflow.com/questions/48710797/how-do-i-deep-clone-an-object-in-react – Archit Sandesara Dec 03 '20 at 04:39