Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  102] [ 5]  / answers: 1 / hits: 25487  / 8 Years ago, thu, october 27, 2016, 12:00:00

I am updating an object within an array in React state using immutability helper.



The object I want to modify is nested:



this.state = {
a: {
b: [{ c: '', d: ''}, ...]
}
}


I want to update the prop c within the nth element of b using immutability helper.



The equivalent code without the immutability helper is:



const newState = Object.assign({}, this.state);
newState.a = Object.assign({}, newState.a);
newState.a.b = newState.a.b.slice();
newState.a.b[n] = Object.assign({}, newState.a.b[n]);
newState.a.b[n].c = 'new value';
this.setState({ newState });


I know the above code is a bit ugly. I am assuming the code using immutability helper will solve my problem. Thanks


More From » reactjs

 Answers
7

One way to do it would be using $set



let index = 0;
let newState = update(this.state, {
a: {
b: {
[index]: {
c: { $set: new value}
}
}
}
});
this.setState(newState);


jsfiddle


[#60262] Monday, October 24, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sylviakaitlinj

Total Points: 564
Total Questions: 114
Total Answers: 105

Location: Jordan
Member since Thu, Aug 11, 2022
2 Years ago
;