ReactJS Spread Operator

1840 views javascript
-4

I am using React.

I have an array of objects in my state.

this.state = {
  team: [{
    name:'Bob',
    number:23
  },
  {
    name:'Jim',
    number:43
  }]
}

When I try to make a copy of the array to change a object's property, I don't get the results I want.

I have tried:

let tempTeam = [...this.state.team]

Any change to tempTeam also mutates this.state.team

AND

let tempTeam = this.state.team.map(player => return {...player}}

This just throws an error, it doesn't like {...player}

How can I get the array of objects without it referencing this.state.team?

answered question

What error does it throw? I can see a syntax error as you have }} instead of }) at the end of the line

3 Answers

0

Using Array.slice() creates a clone, so this should should work:

let tempTeam = this.state.team.slice();

posted this
5

You have a syntax error in the posted code. If you change it to:

let tempTeam = this.state.team.map(player => ({...player}));

Or:

let tempTeam = this.state.team.map(player => { 
                 return { ...player };
               });

You will get a new array with the same object values without the references.

posted this
4

Object.assign and spread syntax create shallow copies. If you mutate a nested property in the copied one you also mutate original object. Most of the time we use map, filter, slice to get a new array by using the original one. But, if you are thinking to create the whole array then mutate it, this is not necessary. You can do the necessary mutations while you are creating it.

As explained you have a syntax error in your code, if you fix it you can get the new array. But, most of the time you will do operations like this one:

const state = {
  team: [{
    name:'Bob',
    number:23
  },
  {
    name:'Jim',
    number:43
  }]
};

const tempTeam = state.team.map( player => ({
  ...player, number: player.number + 1, 
}));


console.log( tempTeam, state.team );

As you can see, you don't create a new array then mutate it, you are mutating it while you are creating it.

posted this

Have an answer?

JD

Please login first before posting an answer.