1

I am trying to combine some of my flat state settings into a settings state object, and at the same time, I want to convert this object to a immutable JS state object.

I get errors though that my key is not defined, although I have set the initial state in the constructor.

Here is what I have so far:

constructor() {
    super();

    this.state = {
        "settings": Immutable.Map() 
    };      
}

Then in componentWillMount (since I get the data from an external API):

componentWillMount() {

    /* Some code */

    this.setState({
        settings: settings.setIn({airlines: Immutable.fromJS(airlines).toList()}),
    });
}

The error I get is: Uncaught ReferenceError: settings is not defined

Btw. the airlines element is an array of objects

Can someone help me out? Is my approach directionally right? And do I need to use updateIn afterwards (on update) once the airlines array is first set and I need to update, or is it safer to use setIn?

user3611459
  • 3,311
  • 6
  • 16
  • 18

2 Answers2

1

settings needs to be referenced like this.state.settings.setIn...

Igorsvee
  • 4,101
  • 1
  • 25
  • 21
1

As the error says, settings is not defined at this position.

Instead, refer to the settings slice of your state:

this.setState({
    settings: this.state.settings.setIn({airlines: Immutable.fromJS(airlines).toList()}),
});

Edit: You are also using ImmutableJS' setIn function incorrectly:

this.setState({
    settings: this.state.settings.setIn(['airlines'], Immutable.fromJS(airlines).toList()),
});

See the docs or this SO answer for more details.

Community
  • 1
  • 1
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
  • great! oww, then I was close ;-) But I do get another error now: Expected iterable or array-like: [object Object]. My airlines variable is an array of 7 objects... any thoughts as well? – user3611459 Jul 19 '16 at 19:51
  • One more question though... I would like to add several elements to my settings object during one setstate call. The following gives me an empty "matchAirlines" object in my array.. Could you tell me if this is the right approach: settings: this.state.settings.setIn(["matchAirlines"], Immutable.fromJS(matchAirlines).toList()), settings: this.state.settings.setIn(["airlines"], Immutable.fromJS(airlines).toList()), – user3611459 Jul 19 '16 at 20:36
  • You should really open a new question, since this goes beyond the scope of what should be discussed in a comment. – TimoStaudinger Jul 19 '16 at 20:41
  • I created the question, which can be found here: http://stackoverflow.com/questions/38468310/add-several-objects-to-immutable-map-within-react-state – user3611459 Jul 19 '16 at 20:53