初始化2

This commit is contained in:
SunYF
2026-08-28 15:06:01 +08:00
parent b34325a16f
commit a9c3fbeb41
537 changed files with 176215 additions and 17 deletions
@@ -0,0 +1,49 @@
import { useEffect, useRef, useState } from 'react';
import { DashboardDataService } from '../services/dashboardService';
import type { DashboardData } from '../types';
export type DataMode = 'sse' | 'polling' | 'init';
interface UseDashboardResult {
data: DashboardData | null;
mode: DataMode;
error: string | null;
retry: () => void;
}
/**
* 订阅看板数据。SSE 优先,失败自动降级为 HTTP 轮询;
* 数据加载失败时暴露 error 与 retry,供 UI 展示重试/错误状态。
*/
export function useDashboardData(): UseDashboardResult {
const [data, setData] = useState<DashboardData | null>(null);
const [mode, setMode] = useState<DataMode>('init');
const [error, setError] = useState<string | null>(null);
const serviceRef = useRef<DashboardDataService | null>(null);
useEffect(() => {
const svc = new DashboardDataService();
serviceRef.current = svc;
const offChange = svc.onChange((d) => {
setData(d);
if (d) setError(null);
});
const offMode = svc.onModeChange((m) => setMode(m));
const offError = svc.onError((msg) => setError(msg));
svc.start();
return () => {
offChange();
offMode();
offError();
svc.stop();
serviceRef.current = null;
};
}, []);
const retry = () => {
setError(null);
serviceRef.current?.retry();
};
return { data, mode, error, retry };
}