0

I have a button that changes increases the value of an object.

<Button bsStyle="info" bsSize="lg" onClick={this.addKoala}>

addKoala:

addKoala: function() {
  this.setState({
    towelCount: this.state.towelCount - 2,
    koalaCount: this.state.koalaCount + 2
  });
  this.handleClick("Koala");
},

I have two values that are in the same ProgressBar, so when you add to one, you need to take from another. That's why I'm taking 2 away from tokel.

it then goes here to be pushed to a firebase backend:

handleClick: function(itemAdded) {
  var style = null;
  if (itemAdded === "Towel") {
    style = "danger"
  } else {
    style = "info"
  }
  this.props.itemsStore.push({
    itemStyle: style,
    text: "A new " + itemAdded + " was rewarded!",
    curItemCount: "It's now: " + this.state.towelCount + " to " + this.state.koalaCount,
  });

  var submitJSON = {
    "koalaCount": this.state.koalaCount,
    "towelCount": this.state.towelCount
  };
  Actions.patchScores(submitJSON);
},

After I refresh the website, the first time I press the button everything works but the values of koala and towel don't change. After that, it works done, but that first time isn't working. Any help would be greatly appreciated!

Elad Karni
  • 145
  • 1
  • 4
  • 17

1 Answers1

0

The setState method has an optional 2nd argumnet that is a callback function to be executed after the setState has been executed and render was called.

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

In your code you handleClick method assumes that setState has been executed and the valaues updated. But there is no guarantee that this is always true. If you provide your handleCLick method as the callBack to setState this can be ensured.

addKoala: function() {
  this.setState({
    towelCount: this.state.towelCount - 2,
    koalaCount: this.state.koalaCount + 2
  },  this.handleClick("Koala").bind(this);
}
jozzy
  • 2,863
  • 3
  • 15
  • 12