import { useCallback, useRef, useState } from "react"; import type { HistoryResponse } from "../../shared/api"; export function useHistory(targetId: number | null) { const [data, setData] = useState({ items: [], total: 0, page: 1, pageSize: 20 }); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); const abortRef = useRef(null); const fetchHistory = useCallback( async (from: string, to: string, page = 1, pageSize = 20) => { if (targetId === null) return; abortRef.current?.abort(); const controller = new AbortController(); abortRef.current = controller; setLoading(true); setError(null); try { const response = await fetch( `/api/targets/${targetId}/history?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&page=${page}&pageSize=${pageSize}`, { signal: controller.signal }, ); if (!response.ok) throw new Error(`HTTP ${response.status}`); const result = (await response.json()) as HistoryResponse; setData(result); } catch (err) { if (err instanceof DOMException && err.name === "AbortError") return; setError(err instanceof Error ? err.message : "请求失败"); } finally { setLoading(false); } }, [targetId], ); return { data, error, loading, fetchHistory }; }