Reputation:
I have a component with a couple a function to increment or decrement a number when the up or down button is clicked.
This is what I've done:
...
this.state = {
score: 50, //The initial number can only go up or down 1
clicked: 0,
};
...then
increment() {
if (!this.state.voted) {
this.setState({
score: this.state.score + 1,
voted: this.state.voted = 1,
});
}
}
decrement() {
if (!this.state.voted) {
this.setState({
score: this.state.score - 1,
voted: this.state.voted = 1,
});
}
}
}
Right now as soon as I click any of the buttons which run either functions it will stop functioning but I need it to work as long as it doesn't go up or down more that 1
So 50 can go to 51 when clicked increment and decrement can only go down to 49
How can I do this?
Upvotes: 0
Views: 1823
Reputation: 7913
Instead of a flag checking if a vote has already occurred, just check that the value is within the correct range. That means you only increment if < 51, and only decrement if > 49.
this.state = {
score: 50, //The initial number can only go up or down 1
clicked: 0,
};
increment() {
if (this.state.score < 51) {
this.setState({
score: this.state.score + 1,
});
}
decrement() {
if (this.state.score > 49) {
this.setState({
score: this.state.score - 1,
});
}
}
If the score could be any value, then simply keep another property, such as defaultScore
which initializes to the same value as score
, and your checks would become score < (defaultScore + 1)
and score > (defaultScore - 1)
.
Upvotes: 1