76 lines
1.8 KiB
TypeScript
76 lines
1.8 KiB
TypeScript
import { create } from "zustand";
|
|
import messageService, { ReddotInfo } from "@/services/messageService";
|
|
|
|
interface MessageState {
|
|
// 红点信息
|
|
reddotInfo: ReddotInfo | null;
|
|
// 是否正在加载
|
|
loading: boolean;
|
|
}
|
|
|
|
interface MessageActions {
|
|
// 获取红点信息
|
|
fetchReddotInfo: () => Promise<void>;
|
|
// 重置红点信息
|
|
resetReddotInfo: () => void;
|
|
// 更新红点信息的某个字段
|
|
updateReddotInfo: (info: Partial<ReddotInfo>) => void;
|
|
}
|
|
|
|
// 完整的 Store 类型
|
|
type MessageStore = MessageState & MessageActions;
|
|
|
|
// 创建 store
|
|
export const useMessageStore = create<MessageStore>()((set, get) => ({
|
|
// 初始状态
|
|
reddotInfo: null,
|
|
loading: false,
|
|
|
|
// 获取红点信息
|
|
fetchReddotInfo: async () => {
|
|
const { loading } = get();
|
|
|
|
// 防止重复请求
|
|
if (loading) return;
|
|
|
|
set({ loading: true });
|
|
|
|
try {
|
|
const res = await messageService.getReddotInfo();
|
|
if (res.code === 0) {
|
|
set({
|
|
reddotInfo: res.data,
|
|
loading: false
|
|
});
|
|
} else {
|
|
set({ loading: false });
|
|
}
|
|
} catch (e) {
|
|
console.error("获取红点信息失败:", e);
|
|
set({ loading: false });
|
|
}
|
|
},
|
|
|
|
// 重置红点信息
|
|
resetReddotInfo: () => {
|
|
set({
|
|
reddotInfo: null
|
|
});
|
|
},
|
|
|
|
// 更新红点信息的某个字段
|
|
updateReddotInfo: (info: Partial<ReddotInfo>) => {
|
|
const { reddotInfo } = get();
|
|
if (reddotInfo) {
|
|
set({
|
|
reddotInfo: { ...reddotInfo, ...info }
|
|
});
|
|
}
|
|
},
|
|
}));
|
|
|
|
// 导出便捷的 hooks
|
|
export const useMessageState = () => useMessageStore((state) => state);
|
|
export const useReddotInfo = () => useMessageStore((state) => state.reddotInfo);
|
|
export const useFetchReddotInfo = () => useMessageStore((state) => state.fetchReddotInfo);
|