Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating the array object in React state using immutability helper

Tags:

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

like image 358
vijayst Avatar asked Oct 27 '16 05:10

vijayst


People also ask

How do I change the state array of objects in React?

To update an object in an array in React state: Use the map() method to iterate over the array. On each iteration, check if a certain condition is met. Update the object that satisfies the condition and return all other objects as is.

What is the use of immutability helper?

Dealing with immutable data in JavaScript is more difficult than in languages designed for it, like Clojure. However, we've provided a simple immutability helper, update() , that makes dealing with this type of data much easier, without fundamentally changing how your data is represented.

What is immutability in Reactjs?

An immutable variable can never be changed. To update its value, you create a new variable. The same applies to objects and arrays. Instead of changing an array, to add a new item you create a new array by concatenating the old array, plus the new item. An object is never updated, but copied before changing it.


2 Answers

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

like image 91
QoP Avatar answered Sep 20 '22 16:09

QoP


Im importing update from immutability helper here :)

this.state = {   a: {     b: [{ c: '', d: ''}, ...]   } }    this.setState((prevState, props) => update(prevState, {     a: {         b: {             $apply: b => b.map((item, ii) => {                 if(ii !== n) return item;                 return {                     ...item,                     c: 'new value'                 }             })         }     } })) 
like image 34
FlatLander Avatar answered Sep 21 '22 16:09

FlatLander