0

I'm using the setState to increment the score of a quiz I made. I'm using the callback method so I don't mutate the data but it's only showing me a score of 2. I don't get what i'm doing wrong here.. I'm calling the calculateScore function whenever the form is submitted onSubmit={this.calculateScore}.


        if(this.state.question1 === '1996') {
            this.setState((curr)=>{
                return {score: curr.score++}
            })
        }

        if(this.state.question2 === 'NWA') {
            this.setState((curr)=>{
                return {score: curr.score++}
            })
        }

        if(this.state.question3 === 'bad-boy') {
            this.setState((curr)=>{
                return {score: curr.score++}
            })
        }

        if(this.state.question4 === 'big-l') {
            this.setState((curr)=>{
                return {score: curr.score++}
            })
        }

        if(this.state.question5 === 'snoop-dogg') {
            this.setState((curr)=>{
                return {score: curr.score++}
            })
        }

        console.log(this.state);
        console.log('calculating')
    }
Brixsta
  • 605
  • 12
  • 24

1 Answers1

1

You are using the postFix operator value++ as opposed to prefix ++value. Try with prefix operator and it should work fine,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment

  • Neither should be used as it mutates state. – zero298 Sep 18 '21 at 20:02
  • This method is still giving me a score of 2 return {score: ++curr.score} – Brixsta Sep 18 '21 at 20:03
  • I was answering what the potential issue might be. However, I agree with @zero298. Better to not mutate and just do `this.setState((curr)=>({score: curr.score + 1}))` – Emmanuel Ponnudurai Sep 18 '21 at 20:06
  • And regarding still not working @Brixsta Where is it not working? You have to check in the callback of setState to see the actual value and not immediately as it may not have performed the state updates at that point. – Emmanuel Ponnudurai Sep 18 '21 at 20:07