0

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

Zalaboza
  • 8,899
  • 16
  • 77
  • 142
  • see https://github.com/reactjs/reselect -- a nice library for creating memoized selectors so that you don't have to worry about them recalculating when the state updates. – elijah Sep 07 '16 at 20:22

1 Answers1

3

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');
Andy Noelker
  • 10,949
  • 6
  • 35
  • 47