简体   繁体   中英

Previous Button is not functioning properly React

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;

Try to change the type of previous button to something else, probably a "button" type will be just fine. Does it help?

Your Previous Question button is inside of your form and you are not using event.preventDefault() in the previousQuestion function so while the previous question function is called the handleSubmit function is also being executed at the same time.

You also call the previousQuestion function without passing the current_question argument. You should grab the currentQuestion from state inside the function, and prevent the default action when clicking the Previous Question button.

You previousQuestion function should look like this:

const previousQuestion = (event) => {
  event.preventDefault();
  let new_current_questions = Math.max(currentQuestion - 1, 0);
  setCurrentQuestion(new_current_questions);
};

That should solve the issue you are having

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM