Immutable.js - toJS Is Not A Function

Kayote picture Kayote · May 4, 2016 · Viewed 13.4k times · Source

I am getting the typeError when I try using this function.

As per the Immutable.js docs, I want to convert an obj into normal JS obj.

Here is the example:

import { Map as iMap,
         toJS } from "immutable";

    let anExample = iMap({
        a : "a",
        b : "b"
    });
    console.log( "anExample is...", toJS( anExample ) );

I do not get an error on Map, but I do on toJS. What am I doing wrong? Thanks,

Answer

Dom picture Dom · May 4, 2016

You do not need to import toJS, since it's found on the immutable object itself. Based on your example, you would go about it like so:

import { Map as iMap } from "immutable";

let anExample = iMap({
    a : "a",
    b : "b"
});
console.log( "anExample is...", anExample.toJS() );

Another way you could go about this is to import fromJS. fromJS is a "lazy" way of converting JS to immutable; however, it is not ideal if you need particular Immutable structures (like an OrderedSet rather than a List).

You would handle that like this:

import { fromJS } from "immutable";

let anExample = fromJS({
    a : "a",
    b : "b"
});
console.log( "anExample is...", anExample.toJS() );

Hope this helps and let me know if you have any questions!