L_K
L_K

Reputation: 2986

Stuck in Immutable.js setIn method

I just test the following code under the Immutable.js docs console in Chrome version 50, but it emit a error message: Uncaught Error: invalid keyPath(…)

var map1 = Immutable.Map({
    a: 1,
    b: {
        c: 1
    }
});

var map2 = map1.setIn(['b', 'c'], 2);

And then I changed the code to :

var map1 = Immutable.fromJS({
    a: 1,
    b: {
        c: 1
    }
});

var map2 = map1.setIn(['b', 'c'], 2);

It just works fine. But why? What's the difference between fromJS and Map?

Upvotes: 1

Views: 734

Answers (2)

hazardous
hazardous

Reputation: 10837

The Map, List and other methods don't deeply convert the given data structure into immutables. In this case, the nested object b remains a plain JavaScript Object within the immutable map map1. Here's a console dump of map1 to depict the same... enter image description here

This is why you should prefer fromJS, which deeply converts the data structure into immutables. Here's a dump of map1 which spawned from the fromJS call - enter image description here

Notice that b is now of the same type (Map minified as Lt) as map1.

There's another way to do deep conversion -

var map1 = Immutable.Map().merge({
    a: 1,
    b: {
        c: 1
    }
});

Note that merge internally invokes fromJS only :).

Upvotes: 3

SimranTea
SimranTea

Reputation: 114

Maybe it is the set path in .Map that is already been used, however it is not in .fromJs

try to change the set path.

Upvotes: 0

Related Questions