You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
update array with objects using Array.prototype.slice
varstate=[{name: "Goran"},{name: "Peter"}]// you can use es6 Array.prototype.findIndex to find index of the object// let index = state.findIndex(({name}) => name === "Peter");varindex=1;varfield='name';varvalue='Zika';varnewState=[
...state.slice(0,index),{
...state[index],[field]: value},
...state.slice(index+1)];console.log(newState);/* [ {name: "Goran"}, {name: "Zika"} ]*/
@gorangajic I may not undertsand this gist, but how come newState is ever immutable ?
Correct me if I am wrong, but doesn't "immutable" means "not mutable" ? If so, then you should try this (based on your examples):
var state = [
{name: "Goran"},
{name: "Peter"}
]
var newState = [
...state.slice(0)
];
state[0].name = "Mutating state, not newState"
console.log(newState);
/*
[
{name: "Mutating state, not newState"},
{name: "Zika"}
]
*/
and print your newState to console: you should see that it has mutated while updating supposedly unrelated state variable :/
Did I miss something ?
Hi @Jonarod! that happens because you are using objects, so the reference to the objects inside the newState array is the same located in state array.
So when you did
var newState = [
...state.slice(0)
]
You are only changing the reference of the array but the reference in objects still remaining the same in both.
That is the reason why in the above example he needs to do this:
{
...state[index],
[field]: value
}
You can see the spread operator in state[index] in order to get a shallow copy of the current object in the state array giving with that a new reference in the newState array.
@gorangajic Typo in the first example "Update object":