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 Update State Based on Previous State

Samuel Marques
Samuel Marques
1,023 Points

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

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

3 Answers

Samuel Marques
Samuel Marques
1,023 Points

I 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
Steven Parker
231,269 Points

Samuel Marques — Glad to help. You can mark a question solved by choosing a "best answer".

And happy coding!

Steven Parker
Steven Parker
231,269 Points

If "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.

I guess a ternary operator also works:

  decrementScore = () => {
    this.setState(prevState => ({
      score: (prevState.score > 0) ? prevState.score - 1 : prevState.score = 0
    }));
  }