Search code examples
javascriptreact-nativeflux

React native setState on compnonentDidMount doesnt work


I am using flux and trying to setState on componentDidMount within my top component in a React Native app. In the constructor , this.state = MainStore.getData(); seems to be setting the state just fine. But for some reason this.setState(data); is not setting the state in my componentDidMount. Here is my code from my top component and my store from my flux pattern.

Component:

constructor(props) {
  super(props);
  this.state = MainStore.getData();
}

componentDidMount() {
  MainStore.addChangeListener(this._onChange);
  var data = MainStore.getUpdatedData();
  console.log('data from store: ',data)
  this.setState(data);
  console.log('state: ',this.state)
}

Store:

var kidsBankData = {
  test:null
};

var kidsData = assign({}, EventEmitter.prototype, {
  getData: function() {
    return kidsBankData;
  },

  getUpdatedData: function(){
    newObj = {
      test:'test'
    }
    return newObj;
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }
});

I am just trying to get the flow working so I am using a test object. Within my component, the first console log that is console logging var data = MainStore.getUpdatedData(); is correctly console logging test:'test' however the second log shows that the state is still test:null which you can see that is initially what is returned in the constructor from the store.

So why is this.setState(data) not updating the state? There are no console errors, it just doesnt set state.


Solution

  • The state is only updated at the end of the componentDidMount method, so you won't see the result immediately in your console.log there. In fact, the react framework aggregates all the state changes and executes them all at once. There are no immediate, intermediary state updates For example if you would do something like this:

    componentDidMount: function() {
      // Get obj1 from some store
      this.setState(obj1)
      // Get obj2 from another store
      this.setState(obj2)
    }
    

    That would be equivalent to:

    componentDidMount: function() {
      // Get obj1 from some store
      // Get obj2 from another store
      this.setState(data1: obj1.data, data2: obj2.data)
    }