value of variable not changing using useState Hook in React JS when implemented using onClick button

Dipesh Ranjan

I implemented a nested ternary operator to render one of 3 things based on condition, it is for the quiz app, one renders the results, on the quiz and one has the option to choose the genre of the quiz.

I defaulted it in such a way that the genre selection defaults, and when the selection is made, clicking the button calls a function that sets the genre's value and changes the variable which essentially changes the ternary operator to change the rendering component.

The problem is genreContainer variable isn't changing from false to true, which is implemented in the function.

import { React, useState } from 'react'
import './quiz.css'
import { QuizData } from '../../data/QuizData'
import Result from '../result/Result'



const Quiz = () => {
    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [score, setScore] = useState(0);
    const [selected, setSelected] = useState(0);
    const [showResult, setShowResult] = useState(0);
    const [currentGenre, setCurrentGenre] = useState(0);
    let genreContainer = false;

    const changeQuestion = () => {
        updateScore();
        if (currentQuestion < QuizData[0].data[currentGenre].length - 1) {
            setCurrentQuestion(currentQuestion + 1);
            setSelected(0);
        }
        else {
            setShowResult(true);
        }

    }

    const genreSelection = () => {
        genreContainer = true;
        setCurrentGenre(selected - 1);
        setSelected(0);

    }

    const updateScore = () => {
        if (selected === QuizData[0].data[currentGenre][currentQuestion].answer) {
            setScore(score + 1)
        }
    }

    return (
        <div className='container'>
            {showResult ? (
                <Result score={score} totalScore={QuizData[0].data[currentGenre].length} />
            ) : (
                <>
                    {genreContainer ? (
                        <>
                            <div className="question">
                                <span id='question-number'>
                                    {currentQuestion + 1}.
                                </span>
                                <span id='question-txt'>
                                    {QuizData[0].data[currentGenre][currentQuestion].question}
                                </span>
                            </div>
                            <div className="option-container">
                                {QuizData[0].data[currentGenre][currentQuestion].options.map((option, i) => {
                                    return (
                                        <button className={`option-btn ${selected === i + 1 ? 'checked' : null}`}
                                            key={i}
                                            onClick={() => setSelected(i + 1)}
                                        >
                                            {option}
                                        </button>
                                    )
                                })}
                            </div>
                            <input type="button" value="Next" id='next-button' onClick={changeQuestion} />
                        </>
                    ) : (
                        <>
                            <div className="question">
                                <span id='question-txt'>
                                    Choose your genre of Quiz
                                </span>
                            </div>
                            <div className="option-container">
                                {QuizData[0].options.map((option, i) => {
                                    return (
                                        <button className={`option-btn ${selected === i + 1 ? 'checked' : null}`}
                                            key={i}
                                            onClick={() => {
                                                setSelected(i + 1);
                                            }}
                                        >
                                            {option}
                                        </button>
                                    )
                                })}
                            </div>
                            <input type="button" value="Select" id='next-button' onClick={genreSelection} />
                            
                        </>
                    )}
                    
                </>
            )}
        </div>
    )
}
export default Quiz

here the genreContainer variable's value isn't changing when genreSelection function is called.

David

The problem is genreContainer variable isn't changing from false to true

Yes it is. But, then you immediately update state. Updating state triggers a re-render. And what does the component do when it renders? This:

let genreContainer = false;

If you want a value to persist across renders, there's a mechanism for that... state. For example:

const [genreContainer, setGenreContainer] = useState(false);

And:

const genreSelection = () => {
    setGenreContainer(true);
    setCurrentGenre(selected - 1);
    setSelected(0);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

react-select default value is not rendered when using useState hook

Changing background image using useState and onClick with React

While using useState hook and onClick event in react I get error when calling the function in onClick event

(Using React) Why is the submit button when onClick is performed using onChange events and resulting in empty string? (useState question)

React - infinite loop using get request when using useState hook

changing multiple states in react js useState() hook

How to disable a button using React useState hook inside event handler

Using array as react hook useState

How to read the value of updated array while using useState hook in react?

React component rendering twice when using useState hook

React state not updated correctly when using useState hook

Support callback for changing another field value when using React Hook Form validation

React changing useState not rendering component when using map to generate elements

How to save and remove value in useState using onClick in React?

How to add to object using react hook useState?

Invalid Hook Call Error when using react useState hook inside firebase app

React hook useState not updating onclick

react js can't update button status using useState

Rendering using useState hook

Using useState hook with TypeScript

Troubles with using hook useState()

The state variable returned after using useState react hook shows .map is not a function

How to type the initial state for react context when using useState as value

How does the const variable 'count' gets updated when using useState() hook

Adding a key-value pair to an object inside loop using React useState hook

Correct way to type nullable state when using React's useState hook

Reading component state just after setting when using useState hook in react

Why does react re-render twice when using the state hook (useState)?

How does useState() in react retrieve the correct state object and function for a functional component when using the state hook?