react-redux: What is the difference between state.setIn() and state.set()?

- 1 answer

Ad

I've seen the use of setIn() and set() in some react-redux code:

state.setIn(...);
state.set(...);

I've found some documentation here https://facebook.github.io/immutable-js/ But unfortunately the method is not documented in detail.

I also found some other questions: Using React's immutable helper with Immutable.js But these do not answer my question.

I understand, that it must do some immutable stuff? But what's the immutable thing here? And what's the difference between set() and setIn()? Why do we need immutable?

Ad

Answer

Ad

Immutable set method only sets immediate properties, I.e. direct children of the object. A setIn let's you set the value of any deep node down the data. set only takes property name. setIn takes an array of keys/index to reach down to the deeply nested element.

var basket = Immutable.Map({"milk":"yes", "flour":"no"});

basket = basket.set("flour", "yes");

basket = Immutable.Map({"fruits":{"oranges":"no"}, "flour":"no"});

basket = basket.setIn(["fruits", "oranges"], "yes");

The getIn/setIn methods are extremely useful when updating states in stores as you can use generic actions and supply the key paths to child components. They can invoke the actions passing the paths as parameters.

Ad
source: stackoverflow.com
Ad