skip to Main Content

I have a quiz there are 4 questions those are dynamic coming from API.

Now when I click on radio button for first question then move to next question again click on previous button then radio is unselecting. Why this happening?

Sandbox URL

Thanks for your efforts!

3

Answers


  1. To keep the selected answer when the user clicks on the previous button, you need to store the user’s selection for each question in the state. Currently, you are storing the selected answer index in the selectedAnswerIndex state variable, but you are resetting it to null when the next button is clicked. Instead, you can store the selected answer for each question in an array and update it whenever the user selects an answer. Here’s how you can modify your code to achieve this:

    1.Add a new state variable called selectedAnswers to store the user’s answers for each question. Initialize it with an empty array:

      const [selectedAnswers, setSelectedAnswers] = useState([]);
    

    2.Modify the handleQuestionInput function to update the selectedAnswers array whenever the user selects an answer:

        const handleQuestionInput = (e) => {
      const index = parseInt(e.target.name);
      const answer = e.target.value;
    
      setSelectedAnswers((prevAnswers) => {
        const newAnswers = [...prevAnswers];
        newAnswers[index] = answer;
        return newAnswers;
      });
    
      setSelectedAnswerIndex(answer);
    };
    

    In this function, we first extract the index of the question from the name attribute of the selected radio button. We then update the selectedAnswers array at that index with the user’s answer. Finally, we update the selectedAnswerIndex state with the user’s answer.

    3.Modify the prevQuestion function to set the current question and selected answer to the previous values stored in the state:

        const prevQuestion = () => {
      setQuestion((currentQuestion) => currentQuestion - 1);
    
      const prevQuestionIndex = question - 1;
      setSelectedAnswerIndex(selectedAnswers[prevQuestionIndex]);
    };
    

    In this function, we first update the question state to the previous question. We then get the index of the previous question and use it to retrieve the selected answer from the selectedAnswers array. We then update the selectedAnswerIndex state with the previous selected answer.

    With these modifications, the user’s selected answer for each question will be stored in the selectedAnswers array and will persist when the user clicks on the previous button.

    Login or Signup to reply.
  2. {
          questionNumber: "2",
          questionType: "MMCQ",
          question: {
            id: 1803,
            questionStem: "Choose two languages you speak?",
            options: "Malayalam,Hindi,Tamil,Kannada,Telungu",
            answers: "Malayalam,Hindi"
          }
    },
    

    Modify this to hold the state of the selected answer,

    NOTE: having correct answers storing the indices can make it easy to decide correct/incorrect answer easily (you can follow your approach also, you have to use string matching instead)

    {
          questionNumber: "2",
          questionType: "MMCQ",
          question: {
            id: 1802,
            questionStem: "Choose two languages you speak?",
            options: "Malayalam,Hindi,Tamil,Kannada,Telungu",
            correctAnswers: [0,1],
            selectedAnswers: [],
          }
    },
    

    onChange of checkbox/radio, set the selected answers’ indices

    {
              questionNumber: "2",
              questionType: "MMCQ",
              question: {
                id: 1802,
                questionStem: "Choose two languages you speak?",
                options: "Malayalam,Hindi,Tamil,Kannada,Telungu",
                correctAnswers: [0,1],
                selectedAnswers: [1,3],
              }
     },
    
    Login or Signup to reply.
  3. You need to add the selections to the state.
    I have taken some liberty to refactor your code to have the questions in the state, this would make is easier to maintain and update

    Edit quiz (forked)

    Explanation on the changes:

    Add selected to the quiz data

    I have added selected: [] to each question in the quiz object.

    Use the quiz in the state

    I have moved your quiz to the state itself

     const [quizQuestions, setQuizQuestions] = useState([...quiz.questions]);
    

    This will let us better control the form

    Control the current question in view

    We can use useMemo to always have the current question available for us to read

     const currentQuestion = useMemo(() => quizQuestions[question].question, [
        question,
        quizQuestions
      ]);
    

    I have moved all logic relying on the question to use this memo

    Set different update methods

    I have updated the code to have update method per type:
    “javascript
    const updateSelection = (e, index) => {
    setQuizQuestions((quizQuestions) => {
    quizQuestions[question].question.selected[index] =e?.target?.checked? e.target.value: null
    return […quizQuestions];
    });
    };
    const updateDropDown = (val, index) => {
    setQuizQuestions((quizQuestions) => {
    if (val) {
    quizQuestions[question].question.selected[index] = val
    } else {
    quizQuestions[question].question.selected[index] = null
    }
    return […quizQuestions];
    });
    };
    const setSelection = (e) => {
    setQuizQuestions((quizQuestions) => {
    quizQuestions[question].question.selected = [e.target.value];
    return […quizQuestions];
    });
    };

    
    This lets us control the selection easily
    
    ## Control each input checked state 
    I have set all inputs to be auto checked using 
    ```javascript
    checked={currentQuestion.selected?.includes(option)}
    

    And in the Select I have used

    <Select
      placeholder="Choose Answer"
      onChange={e=>updateDropDown(e, labelIndex)}
      value={currentQuestion.selected?.[labelIndex]} //<--- look at me!
    >
    

    And now the form is controlled, synced and up to date

    What’s next?

    Now you can put some efforts in cleaning up the code and making it more robust

    Good luck!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search