Ad

How To Properly Pass Immutablejs Object In Flux

I am using react+flux in an application. I am trying to use immutable js to speed up the rendering process as everytime I make any small change to the state, react tries to reconcile all DOMs (which is quite slow).

The problem I am encountering is that inside my store.js, I can convert my state into an immutable Map object. However, as soon as this object is passed to the app, it is no longer recognised as Map object, but just a normal object. This means I cannot use any set or get functions that come with Map object

This is what I have so far:

Store.js

var Immutable = require("immutable");

var Store = function(){   
    var jsState = { object1 : "state of object 1", 
                    object2 : "state of object 2"}
    this.globalState = Immutable.fromJS(globalState);

    this._getGlobalState = function(){
        //console will log: Map { size=2,  _root=ArrayMapNode,  __altered=false,  more...}
        //this.globalState.get("object1"); will work
        console.log(this.globalState); 
        return this.globalState;
    }
}

App.js

var Store = require("./Store.js");
var Map = require("immutable").Map

var App = React.createClass({
    getInitialState: function(){
        return ({});
    },
    componentWillMount: function()
        this._getStateFromStore(); //will get the immutable state from the store
    },
    _getStateFromStore: function()
    {
        return this.setState(Store._getGlobalState());
    },
    render: function(){
        //this will return Object { size=2,  _root=ArrayMapNode,  __altered=false,  more...}
        //this.state.get("object1") will NOT work
        console.log(this.state);
        return <div>This is in App</div>
    }
});

Am I doing something wrong here? Am I missing any modules in any of the files? Many thanks!

Ad

Answer

So, you can't actually force the State object to be an Immutable object. Rather, you have to store Immutable objects within your state.

So, you'll want to do something like:

getInitialState: function(){
  return ({
    data: Immutable.Map({})
  });
},

...
_getStateFromStore: function()
{
  return this.setState({
    data: Store._getGlobalState()
  });
},

Facebook has a good example repo on this subject.

Ad
source: stackoverflow.com
Ad