Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

immutable.js & react.js setState clears prototype of the object

I have the following code in component:

constructor() {
    this.state = Immutable.fromJS({
            user : {
                wasChanged : false,
                firstName : false,
                lastName : false,
                address : {
                    street : false,
                }
            }
        });
}
onEdit({target: {dataset: {target}}}, value) {
      this.setState(function (prevState) {
          return prevState.setIn(['user', target], value);
        });
  }
render() {
    var user = this.state.get('user').toJS();
    ...
}

The problem is that when I try to update the value in onEdit I see that prevState has different prototype set. I don't understand why or what am I doing wrong. I see this in console

> Object.getPrototypeOf(this.state)
src_Map__Map {@@__IMMUTABLE_MAP__@@: true}

> Object.getPrototypeOf(prevState)
Object {}

After the state has been changed it goes to render where it of course can't find get function or anything from Immutable

Using react with addons 0.13.3.

like image 886
Andrey Borisko Avatar asked Feb 10 '23 13:02

Andrey Borisko


1 Answers

Put it as a key on state.

this.state = {
  data: Immutable...
};

Currently the reason you can't use an Immutable object as state is the same reason you can't do this.state = 7: it's not a plain JavaScript object.

Roughly the operation looks like this:

React.Component.prototype.setState = (changes) => {
  batchUpdate(() => {
    // copies own properties from state to the new object
    // and then own properties from changes to the new object
    var nextState = Object.assign({}, state, changes);

    this.componentWillUpdate(...);
    this.state = nextState;
    queueDomUpdateStuff(this.render(), () => this.componentDidUpdate());
  });
};
like image 117
Brigand Avatar answered Feb 12 '23 04:02

Brigand