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 trial

JavaScript React Basics (2018) Understanding State Creating the Application State

-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!

I 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

2 Answers

Using 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Federico Balzi
Front End Web Development Techdegree Graduate 17,395 Points

Hi, this is working for me:

decrementScore = () => { this.setState( prev => { let currentScore = prev.score; if (currentScore > 0) { return { score: currentScore -1 } } }) }