'how to change usestate of state variable in if condition?
I want to change the usestate of quizFinished to true after satisfying the condition in the handleAnswerClick() function. This is the code below .
Note : I am learning react from Codedamn React 18 Video 29
import React, { useState } from 'react'
export default function App() {
// Define a state variable here to track question status
const [quizFinished, setQuizFinished] = useState(false)
const [currentIndex, setCurrentIndex] = useState(0)
function handleAnswerClick() {
// Check if the quiz is over here
if (currentIndex === questions.length) {
setQuizFinished(quizFinished=true)
}
else {
setCurrentIndex(currentIndex + 1);
}
// If yes, set the quizFinished variable to true
// If no, increment the current index like always
}
```
Their is some HTML code below that is in the tutorial. The Tutorial is free.
Solution 1:[1]
Just pass true to setQuizFinished:
setQuizFinished(true)
However, since quizFinished is derived from currentIndex using a state is redundant. Just compute it on each render:
export default function App() {
const [currentIndex, setCurrentIndex] = useState(0)
const quizFinished = currentIndex === questions.length
function handleAnswerClick() {
if(!quizFinished) {
setCurrentIndex(currentIndex => currentIndex + 1);
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ori Drori |
