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 trialCory Aston
6,058 Points-1 for a score
in our class we have the decrementScore function that reduces the score for the player in the component...
decrementScore = () => { this.setState( prevState => ({ score: prevState.score - 1 })); };
But it will allow the score to go below zero. I'm trying to figure out how to zero bound the function. Everything I have tried to include and If {} else {} in the decrementScore leads to a syntax error. How does one go about handling conditionals within state change functions? Sorry if this is answered in later videos!
2 Answers
Mike Straw
7,100 PointsUsing the if
statement with this.state
can work, but you could run into async issues, especially when the score is close to 0, and it's being accessed by multiple players at the same time.
I used ternary operators to implement this:
decrementScore = () => {
this.setState( prevState => ({
score: prevState.score > 0 ? prevState.score - 1 : 0
}));
}
Federico Balzi
Front End Web Development Techdegree Graduate 17,395 PointsHi, this is working for me:
decrementScore = () => { this.setState( prev => { let currentScore = prev.score; if (currentScore > 0) { return { score: currentScore -1 } } }) }
Cory Aston
6,058 PointsCory Aston
6,058 PointsI figured it out... I think...
decrementScore = () => { if (this.state.score > 0) { this.setState( prevState => ({ score: prevState.score - 1 })); }; };
I didn't realize before that I needed to put the IF outside the this.setState function. Is it OK to check the state in the if like I did or will that cause some sort of weird Async problem too?
Thanks Cory