enzostvs's picture
enzostvs HF Staff
init GTM
0738d2d
"use client";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useRouter } from 'next/navigation'
import { PromptType } from "@/utils/type";
import { sleep } from "@/utils";
export const useQuizz = () => {
const client = useQueryClient();
const router = useRouter();
const { data: result } = useQuery<{ success: boolean, id: string} | null>(['success'], () => null, {
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
retry: false,
});
const setResult = (s: string | null, success?: boolean) => {
if (!s) {
client.setQueryData(['success'], null);
return;
}
client.setQueryData(['success'], {
success,
id: s,
});
}
const { data: score } = useQuery<number>(['score'], () => 0, {
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
retry: false,
});
const onScore = async (id?: string) => {
const request = await fetch(`/api/${data?.quest_id}/score`, {
method: 'POST',
body: JSON.stringify({ promptId: id })
});
const response = await request.clone().json().catch(() => ({}));
if (response?.ok) {
client.setQueryData(['score'], (score: number | undefined) => {
return (score ?? 0) + 1;
});
}
const sound = new Audio(response?.ok ? "/success.mp3" : "/lost.mp3");
sound.play();
setResult(response.ok ? id : response.resultId, response?.ok);
await sleep(response.ok ? 2000 : 3000);
if (response?.ok) {
setResult(null);
client.invalidateQueries(['quizz']);
}
};
const { data, isFetching: loading, error, refetch } = useQuery<{ prompts: PromptType[], quest_id: string, question: string }>(['quizz'], async () => {
const request = await fetch(`/api/start`, { method: 'POST', body: JSON.stringify({}) });
const response = await request.clone().json().catch(() => ({}));
return response.data;
}, {
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
retry: false,
});
const reset = () => {
window.location.href = '/';
}
return {
prompts: data?.prompts ?? [],
loading,
error,
question: data?.question,
onScore,
score,
result,
reset
}
}