26

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

1
  • 1
    Consider using ImmutableJS. Commented Oct 27, 2016 at 5:41

2 Answers 2

49

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

Sign up to request clarification or add additional context in comments.

4 Comments

Does update return a new object/element like abc = Object.assign({}, xyz) or it changes the object given as parameter in place??
@VrajSolanki For this example, it will return new state object, with new a object (rest keys are the same, old references), with new b array in it, all of the element refernces wont be changed but [index] one. And with new reference for c, the rest will be old references.
@VrajSolanki the $set command will "replace the target entirely". The $merge command will merge the keys of object with the target. github.com/kolodny/immutability-helper#available-commands
Don't forget to import "update" from immutability-helper. import update from 'immutability-helper';
9

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'
                }
            })
        }
    }
}))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.