Search code examples
reactjsreduxreact-redux

How to reset state on submit button sreact redux


I have been struggling to reset the state on handleSubmit function. There are 3 questions that are coming one by one and on submit the next 3 questions should come like 1/3, 2/3 and 3/3 and this process goes on till all the questions are not submitted. Here is the code below:

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 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));
        }
// this i added to get the question process repeat as earlier, but not working.
    setCurrentQuestion((current) => {
            return Math.min(
              current + 1,
              questions.length - 1
            );
          });
    };
    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 */}
                    {questions.map((question, index) => {return 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;

As user submitted the form, the question should appear one by one and if user refresh the page in between it should show the same page where he lefts, not the new url. Please help


Solution

  • Your handleSubmit should reset the state to 0:

    const 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));
        }
        // Reset to zero, and let handleRadioChange increase it
        setCurrentQuestion(0);
    };
        ```