generated from muhtadeetaron/nextjs-template
fix(nav): fix exam flow navigation
chore(zustand): refactor auth code for zustand store
This commit is contained in:
@ -1,12 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { create } from "zustand";
|
||||
import { Test, Answer, Question } from "@/types/exam";
|
||||
import { Test, Answer } from "@/types/exam";
|
||||
import { API_URL, getToken } from "@/lib/auth";
|
||||
import { ExamResult } from "@/types/exam";
|
||||
|
||||
// Result type (based on your API response)
|
||||
|
||||
type ExamStatus = "not-started" | "in-progress" | "finished";
|
||||
|
||||
interface ExamState {
|
||||
@ -69,35 +67,31 @@ export const useExamStore = create<ExamState>((set, get) => ({
|
||||
// submit exam
|
||||
submitExam: async (testType: string) => {
|
||||
const { test, answers } = get();
|
||||
if (!test) return null;
|
||||
if (!test) throw new Error("No test to submit");
|
||||
|
||||
const token = await getToken();
|
||||
|
||||
try {
|
||||
const { test_id, attempt_id } = test.metadata;
|
||||
const res = await fetch(
|
||||
`${API_URL}/tests/${testType}/${test_id}/${attempt_id}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ answers }),
|
||||
}
|
||||
);
|
||||
const { test_id, attempt_id } = test.metadata;
|
||||
const res = await fetch(
|
||||
`${API_URL}/tests/${testType}/${test_id}/${attempt_id}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ answers }),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) throw new Error("Failed to submit exam");
|
||||
const result: ExamResult = await res.json();
|
||||
if (!res.ok) throw new Error("Failed to submit exam");
|
||||
|
||||
// save result, clear test+answers
|
||||
set({ test: null, answers: [], result });
|
||||
const result: ExamResult = await res.json();
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
console.error("Failed to submit exam. Reason:", err);
|
||||
return null;
|
||||
}
|
||||
// save result only
|
||||
set({ result });
|
||||
|
||||
return result;
|
||||
},
|
||||
|
||||
// cancel exam
|
||||
|
||||
Reference in New Issue
Block a user