I have a quiz page, where every time 3 questions will load one by one and on submit next 3 questions will load. On click of previous user can change his/her answer selected before clicking the submit button. But in the code the previous button is not functioning properly. After 5-6 click on previous button the user is redirected to next page. User can go on next page only after completing the quiz. but this is not happening. please help me out to figure out what is wrong in the code.
const Quiz = () => {
const { questions, quiz, options } = useSelector((state) => state.quiz);
const [currentQuestion, setCurrentQuestion] = useState(0);
console.log(currentQuestion[number] + "1q");
const dispatch = useDispatch();
const history = useHistory();
const location = useLocation();
const classes = useStyles();
// this is to get the questions from the history coming from redux store.
useEffect(() => {
if (!questions) {
dispatch(fetchQuestions(history));
}
}, []);
const handleRadioChange = (number, event) => {
let currentSelection = questions.find(question => question.number === number);
console.log(currentSelection + "radio selected");
currentSelection.value = event.target.value;
console.log(currentSelection.value + "calculate score");
// Set the new question count based on the current one
setCurrentQuestion((current) => {
return Math.min(
current + 1,
questions.length - 1
);
});
};
const previousQuestion = (current_question) => {
let new_current_questions = Math.max(current_question - 1, 0);
setCurrentQuestion(new_current_questions);
};
function handleSubmit(event) {
event.preventDefault();
const valid = questions.some((q) => !q.value);
console.log(valid + "questionsalpha");
if (!valid) {
dispatch(postQuiz({ responses: questions, id: quiz.id }, history));
}
setCurrentQuestion(0);
}
return (
!questions?.length ? <CircularProgress /> : (
<Grid className={classes.container} container alignItems="stretch" spacing={1}>
<form onSubmit={handleSubmit}>
{/* Only show the question if it's index is less than or equal to the current question */}
<button type="submit" onClick={previousQuestion}>{current_question+1 ? 'Previous' : null}</button>
{questions.map((question, index) => (index <= currentQuestion ? (
<FormControl component="fieldset" key={question.number} className={classes.formControl} data-hidden={question.number !== current_question[question.number]}>
<FormLabel component="legend">{question.question}</FormLabel>
<RadioGroup aria-label="quiz" name="quiz" value={question.value} onChange={(e) => handleRadioChange(question.number, e)}>
{options.map((option) =>
<FormControlLabel key={option.score} value={option.score} control={<Radio />} label={option.label} />
)}
</RadioGroup>
</FormControl>
) : null))}
<Button type="submit" variant="outlined" color="primary" className={classes.button}>
Submit
</Button>
</form>
</Grid>
)
);
};
export default Quiz;