I am practicing React using Hooks and Context, working on a simple Quiz App. The score should increment to 1 when the answer is correct.
const { qa, questionNumber } = useContext(GlobalContext);
const [score, setScore] = useState(0);
const answerOnClick = (e) => {
const correct = qa[questionNumber].correct_answer === e ? true : false;
if (correct) {
setScore(() => score++);
}
};
But I'm getting this error on line setScore(() => score++);
:
TypeError: Assignment to constant variable
I also tried if (correct) { score++; setScore(() => score); }
and setScore(() => ++score)
, still not working.
But when I try setScore(() => score + 1);
, now it increments!
I have learned that the Increment is a valid JS operator. Aren't score++
and score + 1
equivalent? And why score
treat as a constant variable? It is mutable, right? I'm still a novice developer. Can someone explain what's happening here? Thank you.