Momen Zalabany
Momen Zalabany

Reputation: 9007

updated nested Immutable in immutable.js

how can i update a nested immutable Map item without mutatiling the whole tree ?

example :

var tree = Map({
 branch1:Map([]),
 branch2:Map({ 1: Map({id:1,value:'hello'}) }),
});

how can i update tree.branch2.1.value ?

will this cause branch1 to get a new copy ?

i'm using this in a Reactjs Redux app. since i'm also using selectors, i want to change value of branch2 without changin branch1 also, so that selectors wonnt recalculate again

Upvotes: 0

Views: 97

Answers (1)

Andy Noelker
Andy Noelker

Reputation: 11269

Changing values in an Immutable.js object will always return a completely new object instead of mutating it. That's essentially the whole point of the library. If you are worried about unnecessary re-renders based on other aspects of your state changing, you should use the shouldComponentUpdate lifecycle method to ensure that your components only update when the value of that part of the app state changes, and not simply when it is a new object.

For your case, it would make the most sense to use the setIn method for Immutable maps.

tree.setIn(['branch2', 1, 'value'], 'newValue');

Upvotes: 3

Related Questions