Array not updating on useState

Viewed 43

I'm creating a quiz with questions and answers. On each question, I compare if the answer is correct, and if it's correct I update the score and save the answer given on an array.

When I try to add the answer to the array, it's not saved until the form it's submitted again. I have tried to fix this with useEffect, however, I don't know exactly how to do it correctly.

I would appreciate any help

import React, { useState } from 'react';

import Radio from './Radio';
import { quizQuestions } from '../utils/quizQuestions';

const Question = ({number, question, setNumber, setData, data, order }) => {
    const [input, setInput] = useState("");

    const handleSubmit = (event) => {
        event.preventDefault();
        let newPage = number;
        newPage++;
        setNumber(newPage);
        getNextStep();
    }
    const handleInputChange = (event) => {
        setInput(Number(event.target.value));
    }

    const getNextStep = () => {
        let newAnswer = [...data.answers, input]
        let newScore = quizQuestions[order[number]].correct === input ? data.score + 1 : data.score;
        setData(prevState => ({
            ...prevState,
            score: newScore,
            answers: newAnswer
        }));
    }

    return (
        <>
                <form className="bs-component" onSubmit={(event) => handleSubmit(event)}>
                    <div className="jumbotron">
                        <h1 className="display-3">{question.title}</h1>
                        <div className="btn-group btn-group-toggle" data-toggle="buttons">
                            {question.answers.map((element, index) => (
                                <Radio element={element} index={index} key={index} number={number} handleInputChange={handleInputChange}/>
                            ))}
                        </div>
                        <button className="btn btn-primary btn-lg" type="submit">Next</button>
                    </div>
                </form>
        </>
    );
}

export default Question;
0 Answers
Related