Search code examples
javascriptreactjs-fluxreactjs

this.state.foo is different in _onChange and different in render()?


In _onChange method, I wait for a change in this.state.name. On the change _updateArticle method is called:

_onChange() {

        var team = this.getTeamState();
        this.setState({name: team});
        console.log(this.state.name); //"Boston Celtics" //this should have changed but it didn't 
        this.unbind("articles");
        this._updateArticle();
    },

then in _updateArticle a new reference is created using this new state.

_updateArticle(team) {
        var teamRef = new Firebase(this.props.baseUrl + team + "/results");
        console.log(this.state.team); // "Boston Celtics" //this should have been new but its not
        this.bindAsArray(teamRef, 'articles');

    },

In render method however just to check the state I put console.log to check. In render, this.state.name has been updated properly. My question is why is this.state different outside of render function?.


Solution

  • As per the API docs:

    setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

    If you really want to access state right after calling setState, use the callback parameter in the setState method:

    setState(function|object nextState[, function callback])

    So your code should look like:

    _onChange() {
      var team = this.getTeamState();
      this.setState({name: team}, function() {
        console.log(this.state.name);
        this.unbind("articles");
        this._updateArticle(this.state.team);
      });
    }
    

    Hope this helps.