49 lines
1.4 KiB
TypeScript
49 lines
1.4 KiB
TypeScript
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 };
|
|
} |