frontAnswerer/lib/api/hooks.ts
Nastya dea576f164
All checks were successful
Deploy / CreateImage (push) Successful in 4m28s
Deploy / DeployService (push) Successful in 24s
Merge branch 'alone' into staging
2025-06-30 05:12:04 +03:00

88 lines
3.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import useSWR from "swr";
import { getAndParceData } from "./quizRelase";
import { useEffect, useState } from "react";
import { initDataManager, statusOfQuiz } from "@/utils/hooks/useQuestionFlowControl";
import { addQuestions, setQuizData, useQuizStore } from "@/stores/useQuizStore";
/*
У хука есть три режмиа работы: "line" | "branch" | "ai"
Для branch и line единовременно запрашиваются ВСЕ данные (пока что это количество на 100 штук. Позже нужно впилить доп запросы чтобы получить все вопросы.)
Для ai идёт последовательный запрос данных. При первом попадании на result - блокируется возможность запрашивать новые данные
*/
export function useQuizData(quizId: string, preview: boolean = false) {
const { quizStep, questions } = useQuizStore();
const [page, setPage] = useState(0);
const [needFullLoad, setNeedFullLoad] = useState(false);
useEffect(() => {
if (quizStep > page) setPage(quizStep);
}, [quizStep]);
return useSWR(
preview ? null : ["quizData", quizId, page, needFullLoad],
async ([, id, currentPage, fullLoad]) => {
// Первый запрос - получаем статус
if (currentPage === 0 && !fullLoad) {
const firstData = await getAndParceData({
quizId: id,
limit: 1,
page: currentPage,
needConfig: true,
});
//firstData.settings.status = "ai";
initDataManager({
status: firstData.settings.status,
haveRoot: firstData.settings.cfg.haveRoot,
});
setQuizData(firstData);
// Определяем нужно ли загружать все данные
console.log("Определяем нужно ли загружать все данные");
console.log(firstData.settings.status);
if (!["ai"].includes(firstData.settings.status)) {
setNeedFullLoad(true); // Триггерит новый запрос через изменение ключа
return firstData;
}
return firstData;
}
// Полная загрузка для line/branch
if (fullLoad) {
const data = await getAndParceData({
quizId: id,
limit: 100,
page: 0,
needConfig: false,
});
addQuestions(data.questions.slice(1));
return data;
}
if (currentPage >= questions.length) {
try {
// Для AI режима - последовательная загрузка
const data = await getAndParceData({
quizId: id,
page: currentPage,
limit: 1,
needConfig: false,
});
addQuestions(data.questions);
return data;
} catch (_) {
setPage(questions.length);
}
}
},
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
shouldRetryOnError: false,
refreshInterval: 0,
}
);
}