Closed lemonzeng closed 1 month ago
实现了,但是加载好慢,得优化。
const fetchQuizzes = async () => {
const quizzes = await client.findQuizzesForCourse(cid as string);
const quizData: {
[key: string]: {
questionCount: number;
score?: number | null;
total?: number | null;
};
} = {};
if (role === "FACULTY") {
// FACULTY: 只获取 questionCount,不需要 fetch score 和 total
for (let quiz of quizzes) {
const questionSet = await client.getQuestionsByQuiz(quiz._id);
quizData[quiz._id] = {
questionCount: questionSet.questions ? questionSet.questions.length : -1,
};
}
dispatch(setQuizzes(quizzes));
} else if (role === "STUDENT") {
// STUDENT: 只展示 published 的 quizzes,同时获取 questionCount、score 和 total
const publishedQuizzes = quizzes.filter((q: any) => q.published);
for (let quiz of publishedQuizzes) {
const questionSet = await client.getQuestionsByQuiz(quiz._id);
const questionCount = questionSet.questions ? questionSet.questions.length : -1;
let score = null;
let total = null;
if (questionCount !== -1) {
const result = await getLatestAnswerScoreAndTotal(quiz._id, userId);
if (result) {
score = result.score;
total = result.total;
} else {
score = -1;
total = -1;
}
}
quizData[quiz._id] = {
questionCount,
score,
total,
};
}
dispatch(setQuizzes(publishedQuizzes));
}
// 保存 quizData
setQuizData(quizData);
};
// Function to get the latest answer score and total
const getLatestAnswerScoreAndTotal = async (qid: string, userId: string) => {
if (!qid || !userId) {
console.error('Quiz ID or User ID is undefined');
return null;
}
try {
const answers = await client.getAnswersByUser(qid, userId);
if (answers && answers.length > 0) {
answers.sort(
(a: Answers, b: Answers) => +new Date(b.submit_time) - +new Date(a.submit_time)
);
const newestAnswer = answers[0];
const score = newestAnswer.score;
const total = newestAnswer.total;
return { score, total };
} else {
console.log("No answers found for this quiz.");
return null;
}
} catch (error) {
console.error('Error fetching answers:', error);
return null;
}
};
if (Object.keys(quizData).length < 1) return <div>Loading...</div>;
你的pr这一行加了下缓加载页面处理,目前先这样吧,因为这个需求确实没有明显的优化方案