canina/frontend/application/lib/store/settingsStore.ts

61 lines
1.6 KiB
TypeScript

"use client";
import { create } from "zustand";
import api from "../services/api";
export interface ScientificTerm {
key: string;
term: string;
definition: string;
wikiId: string;
}
interface SettingsStore {
texts: Record<string, string>;
scientificTerms: Record<string, ScientificTerm>;
isLoading: boolean;
fetchSettings: () => Promise<void>;
getText: (key: string, fallback: string) => string;
}
export const useSettingsStore = create<SettingsStore>()((set, get) => ({
texts: {},
scientificTerms: {},
isLoading: false,
fetchSettings: async () => {
set({ isLoading: true });
try {
const [textsRes, termsRes] = await Promise.all([
api.get('/settings/ui-texts'),
api.get('/settings/scientific-terms'),
]);
const textsObj: Record<string, string> = {};
if (Array.isArray(textsRes.data)) {
textsRes.data.forEach((item: { key: string; value: string }) => {
textsObj[item.key] = item.value;
});
}
const termsObj: Record<string, ScientificTerm> = {};
if (Array.isArray(termsRes.data)) {
termsRes.data.forEach((item: ScientificTerm) => {
termsObj[item.key] = item;
});
}
set({ texts: textsObj, scientificTerms: termsObj });
} catch (error) {
console.error("Failed to fetch settings/ui-texts:", error);
} finally {
set({ isLoading: false });
}
},
getText: (key, fallback) => {
const value = get().texts[key];
if (value === undefined || value === null) {
return fallback;
}
return value;
}
}));