| 1 | "use client"; |
| 2 | |
| 3 | import { useState, useEffect, useCallback } from "react"; |
| 4 | import { health } from "@/lib/mock-gateway"; |
| 5 | import type { HealthResponse } from "@/lib/types"; |
| 6 | |
| 7 | interface UseHealthReturn { |
| 8 | data: HealthResponse | null; |
| 9 | loading: boolean; |
| 10 | error: string | null; |
| 11 | refresh: () => Promise<void>; |
| 12 | } |
| 13 | |
| 14 | export function useHealth(pollIntervalMs = 30_000): UseHealthReturn { |
| 15 | const [data, setData] = useState<HealthResponse | null>(null); |
| 16 | const [loading, setLoading] = useState(true); |
| 17 | const [error, setError] = useState<string | null>(null); |
| 18 | |
| 19 | const refresh = useCallback(async () => { |
| 20 | try { |
| 21 | const result = await health(); |
| 22 | setData(result); |
| 23 | setError(null); |
| 24 | } catch (err) { |
| 25 | setError(err instanceof Error ? err.message : "Health check failed"); |
| 26 | } finally { |
| 27 | setLoading(false); |
| 28 | } |
| 29 | }, []); |
| 30 | |
| 31 | useEffect(() => { |
| 32 | refresh(); |
| 33 | const interval = setInterval(refresh, pollIntervalMs); |
| 34 | return () => clearInterval(interval); |
| 35 | }, [refresh, pollIntervalMs]); |
| 36 | |
| 37 | return { data, loading, error, refresh }; |
| 38 | } |