Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spread Operator Dynamic Properties Update

I have a state that looks like this:

state: {
    1: {show: false, description: 'one'},
    2: {show: false, description: 'two'},
    3: {show: true, description: 'three'}
   }

Depending on a variable "id" that comes from the action, I have to update the state.

Something like this:

var returnedState = {...state, [id].show : ![id].show}

How can I do this?

like image 989
Diego Unanue Avatar asked Jan 26 '17 20:01

Diego Unanue


People also ask

Does spread operator overwrite property?

Using the spread operator to overwrite an object property It's a super clean syntax and easy to see which value we are overwriting. The only thing you must remember while using this method is that the order matters. If we, for instance, put the property we want to overwrite.

Does spread operator change reference?

When you have nested data in an array or object the spread operator will create a deep copy of the top most data and a shallow copy of the nested data. lets take a look at what this means. this changes the reference at d[2] to a new array created with the spread operator!

Does IE 11 support spread operator?

Spread properties is a part of ECMAScript 2018 which is not supported by IE.

Does object spread overwrite?

You can also mix in other properties with the object spread operator. Order matters: the object spread operator will overwrite properties that are defined before it, but not after.


1 Answers

{...state,
 [id]: {
  show: !state[id].show 
 }
}

that will copy the original state and then toggle the show value for the specific key/id that came from the action.

Here is a working code pen http://codepen.io/finalfreq/pen/mRBjZV

like image 111
finalfreq Avatar answered Sep 22 '22 11:09

finalfreq