42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
import { useState } from 'react';
|
|
import { useNavigate } from 'react-router';
|
|
import { toast } from 'sonner';
|
|
import { api, errorMessage } from '@/lib/api';
|
|
import { useRefresh } from '@/lib/queries';
|
|
import type { Attempt } from '@/lib/types';
|
|
|
|
export type AttemptSource =
|
|
| { type: 'quiz'; quizId: string }
|
|
| { type: 'retake'; attemptId: string }
|
|
| { type: 'missed'; classId?: string; quizId?: string }
|
|
| { type: 'topics'; classId: string; topics: string[] }
|
|
| { type: 'questions'; questionIds: string[]; title?: string };
|
|
|
|
export interface StartOptions {
|
|
mode?: 'practice' | 'exam';
|
|
source: AttemptSource;
|
|
shuffleQuestions?: boolean;
|
|
shuffleOptions?: boolean;
|
|
count?: number;
|
|
timeLimitMin?: number | null;
|
|
}
|
|
|
|
/** Starts a quiz session and opens it. */
|
|
export function useStartSession() {
|
|
const navigate = useNavigate();
|
|
const refresh = useRefresh();
|
|
const [starting, setStarting] = useState(false);
|
|
const start = async (opts: StartOptions) => {
|
|
setStarting(true);
|
|
try {
|
|
const res = await api.post<{ attempt: Attempt }>('/api/attempts', { mode: 'practice', ...opts });
|
|
void refresh();
|
|
navigate(`/session/${res.attempt.id}`);
|
|
} catch (e) {
|
|
toast.error(errorMessage(e));
|
|
} finally {
|
|
setStarting(false);
|
|
}
|
|
};
|
|
return { start, starting };
|
|
}
|