Jason Chen
Jason Chen

Reputation: 2577

Reactjs add a number to a state?

say I had a Reactjs state that was organized like so:

getInitialState: function(){
return {food: ''}
}

How would I add conditional number values to that state? Say something like:

firstset: function(){
this.setState({food: +9});
}

And

secondset:function(){
this.setState({food: +10});
}

I would like to know how I would go about iterating these numbers to the state of 'food' when the firstset function is activated, along with the secondset. So the consequence of activating them both once is 9+10, which would make food: 19.

Upvotes: 2

Views: 5495

Answers (2)

webdeb
webdeb

Reputation: 13211

First of all, food should be initially set as Number:

getInitialState: function(){
  return {
    food: 0
  }
}

Then to add some value to something you need the value.. so just take the this.state.food value..

incBy: function(value) {
   this.setState({
     food: this.state.food + value
   });
}

Upvotes: 2

TimoStaudinger
TimoStaudinger

Reputation: 42460

You can refer to the previous state while setting it:

getInitialState: function() {
  return {
    food: 0
  }
}

firstSet: function() {
  this.setState({
    food: this.state.food + 9
  })
}

secondSet: function() {
  this.setState({
    food: this.state.food + 10
  })
}

Upvotes: 3

Related Questions