Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Basics Understanding State Creating the Application State

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

Cory Aston
Cory Aston
6,058 Points

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

1 Answer

Mike Straw
Mike Straw
6,750 Points

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
        }));
    }