P.Brian.Mackey
P.Brian.Mackey

Reputation: 44285

Possible race condition calling setState

displayModal has a value that is always a value behind. Possibly a race condition. I call updateModal in the callback for setState so a race condition should not happen.

      addAccrual: function() {
        console.log('setting modal to display true');
          this.setState({displayModal: 1}, this.updateModal());
      },

      saveAddAccrual: function() {
        console.log('setting modal to display false');
          this.setState({displayModal: 0}, this.updateModal());
      },

      cancelAddAccrual: function() {
        console.log('setting modal to display false');
          this.setState({displayModal: 0}, this.updateModal());
      },

  updateModal: function() {
    console.log("state of displayModal: " + this.state.displayModal);
    if(this.state.displayModal){
      console.log('showing modal');
      $('#myModalOverlay').show();
      $('#myReactModal').show();
    }else{
      console.log('hiding modal');
      $('#myModalOverlay').hide();
      $('#myReactModal').hide();
    }
  },

E.G.

Setting modal to display true
state of displayModal: 0
hiding Modal

HTML/JSX

<button className="ay-btn" id="addAccrualButton" onClick={this.addAccrual}>Add Accrual</button>

<button className="btn" type="button" onClick={this.cancelAddAccrual}><i className="icon-remove"></i>Cancel</button>

<button className="btn-primary btn" type="button" onClick={this.saveAddAccrual}><i className="icon-white icon-ok"></i>Save</button>

Upvotes: 1

Views: 365

Answers (1)

rossipedia
rossipedia

Reputation: 59397

Your problem is probably this:

this.setState({displayModal: 1}, this.updateModal());

I assume you want to call updateModal after the state has successfully been set. the above line doesn't do that, since you're passing the result of updateModal as a callback.

Change it to:

this.setState({displayModal: 1}, this.updateModal); // no ()

and you should see the behavior you expect.

Upvotes: 2

Related Questions