Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSamuel Marques
1,023 PointsHow to make the decrement not exceed 0?
If the score has reached 0, how to do it if the user continues clicking on the "-", the score does not go to -1, -2, -3 etc.
I tried this, but not working:
decrementScore() {
this.setState( prevState => {
if (prevState >= 0) {
return {
score: prevState.score - 1
}
}
})
}
Thanks!
3 Answers
Samuel Marques
1,023 PointsI put together the two answers and it was like this:
decrementScore() {
this.setState( prevState => {
if (prevState.score !== 0) {
return {
score: prevState.score - 1
}
}
})
}
Thanks Guys; Works fine now
Steven Parker
231,269 PointsSamuel Marques — Glad to help. You can mark a question solved by choosing a "best answer".
And happy coding!
Steven Parker
231,269 PointsIf "prevState" is an object that contains a "score" property, you wouldn't want to compare it directly to a numeric value. You should compare its "score" property instead.
But you can simplify the process a bit by checking the value before you call "setState", and only call it if the current value is greater than 0.
Matthew Conrad
28,069 PointsI guess a ternary operator also works:
decrementScore = () => {
this.setState(prevState => ({
score: (prevState.score > 0) ? prevState.score - 1 : prevState.score = 0
}));
}
Joshua Blasbalg
Full Stack JavaScript Techdegree Graduate 22,583 PointsJoshua Blasbalg
Full Stack JavaScript Techdegree Graduate 22,583 Pointshey samuel! without seeing the rest of your code, i would try (prevState != 0), so that if prevState is 0, the function won't work so it will never go to negative!