46 lines
1.5 KiB
TypeScript
46 lines
1.5 KiB
TypeScript
import { create } from "zustand";
|
|
import { CourseSummary } from "shared/domain/summary";
|
|
import {
|
|
getSummaryContent
|
|
} from "../queries/CRUD-Summaries";
|
|
|
|
interface SummaryState {
|
|
content: Record<number, string>;
|
|
loading: Record<number, boolean>;
|
|
error: Record<number, string | null>;
|
|
setContent: (summaryId: number, content: string) => void;
|
|
fetchContent: (summary: CourseSummary) => Promise<void>;
|
|
}
|
|
|
|
export const useSummaryStore = create<SummaryState>((set) => ({
|
|
content: {},
|
|
loading: {},
|
|
error: {},
|
|
setContent: (summaryId, content) =>
|
|
set((state) => ({
|
|
content: { ...state.content, [summaryId]: content },
|
|
})),
|
|
fetchContent: async (summary) => {
|
|
if (!summary?.summary_id) return;
|
|
set((state) => ({
|
|
loading: { ...state.loading, [summary.summary_id!]: true },
|
|
error: { ...state.error, [summary.summary_id!]: null },
|
|
}));
|
|
try {
|
|
const content = await getSummaryContent(summary);
|
|
set((state) => ({
|
|
content: { ...state.content, [summary.summary_id!]: content ?? "" },
|
|
}));
|
|
} catch (e: any) {
|
|
set((state) => ({
|
|
error: { ...state.error, [summary.summary_id!]: e?.message || "Failed to load summary" },
|
|
content: { ...state.content, [summary.summary_id!]: "" },
|
|
}));
|
|
} finally {
|
|
set((state) => ({
|
|
loading: { ...state.loading, [summary.summary_id!]: false },
|
|
}));
|
|
}
|
|
}
|
|
}));
|