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