Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does getIn() do in Immutable.js?

Tags:

Unfortunately the documentation is very sparse :

https://facebook.github.io/immutable-js/docs/#/Map/getIn

Does anyone have an example? I am guessing that if I have a myObject like so :

  a: {     b:{       c:"banana"     }   } 

that

myObject.getIn(["a", "b", "c"])

will return banana.

However the immutable objects can also be map objects which leaves me thoroughly confused.

like image 966
Oliver Watkins Avatar asked Apr 20 '17 09:04

Oliver Watkins


People also ask

What is fromJS in immutable?

fromJS() Deeply converts plain JS objects and arrays to Immutable Maps and Lists.

How does immutable JavaScript work?

When possible, Immutable. js avoids creating new objects for updates where no change in value occurred, to allow for efficient reference equality checking to quickly determine if no change occurred.

Is immutable JS dead?

Update on 12 Aug 2021. Happily, the creator of Immutable JS resumed to maintaining his lib, and commits are regular now.

Should I use immutable JS?

Using ImmutableJS can improve dramatically the performance of your application. And, because the immutable data never changes, you can always expect new data to be passed from the above. To make sure you are correctly comparing the data and not updating the UI when there is no change, you should always use the .


Video Answer


1 Answers

Shortly:

map.getIn(["a", "b", "c"]) is a shortcut to map.get("a").get("b").get("c")

In details:

You have probably got into one of the fromJS traps. Calling :

const map = Immutable.fromJS({a: {b: {c: "banana"}}}); 

creates a Map with only key a, which's value is also a Map with only key b, which's value is also a Map with only key c and value banana.

With other words fromJS goes into the deep of the object provided, and defines Map for each Object and a List for each Array

With this example, calling map.getIn(["a", "b", "c"]) is kind of a shortcut to map.get("a").get("b").get("c")

But if you define map as a Map:

const map = new Immutable.Map({a: {b: {c: "banana"}}}); 

it creates a Map, with only key a, which's value is plain object {b: {c: "banana"}}, and calling a map.get("a").get("b").get("c") will throw you something like get is not a function, since map.get("a") will return {b: ...} plain object.

Same reasons are why map.getIn(["a", "b", "c"]) will not work as you might expect.

like image 168
Jevgeni Avatar answered Nov 25 '22 07:11

Jevgeni