1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| const { mutate: checkAnswer, isPending: isChecking } = useMutation({ mutationFn: async () => { const payload: z.infer<typeof checkAnswerSchema> = { questionId: currentQuestion.id, userInput: options[selectedChoice], }; const response = await axios.post(`/api/checkAnswer`, payload); return response.data; }, });
const { mutate: endGame } = useMutation({ mutationFn: async () => { const payload: z.infer<typeof endGameSchema> = { gameId: game.id, }; const response = await axios.post(`/api/endGame`, payload); return response.data; }, });
const handleNext = React.useCallback(() => { checkAnswer(undefined, { onSuccess: ({ isCorrect }) => { if (isCorrect) { setStats((stats) => ({ ...stats, correct_answers: stats.correct_answers + 1, })); toast("Correct",{ description: "You got it right!", }); } else { setStats((stats) => ({ ...stats, wrong_answers: stats.wrong_answers + 1, })); toast("Incorrect",{ description: "You got it wrong!", }); }
if (questionIndex === game.questions.length - 1) { endGame(); setHasEnded(true); return; } setQuestionIndex((questionIndex) => questionIndex + 1); setSelectedChoice(0); }, }); }, [checkAnswer, questionIndex, game.questions.length, toast, endGame]);
... <Button variant="default" className="mt-2" size="lg" disabled={isChecking || hasEnded} onClick={() => { handleNext(); }} > {isChecking && <Loader2 className="w-4 h-4 mr-2 animate-spin" />} Next <ChevronRight className="w-4 h-4 ml-2" /> </Button>
|