Add src/hooks/useStatus.ts
This commit is contained in:
parent
3d524bd05e
commit
6d235f7d07
1 changed files with 30 additions and 0 deletions
30
src/hooks/useStatus.ts
Normal file
30
src/hooks/useStatus.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { useEffect, useState, useCallback } from "react";
|
||||||
|
import { api, AppStatus, Host } from "../api";
|
||||||
|
|
||||||
|
export function useStatus(pollMs = 3000) {
|
||||||
|
const [status, setStatus] = useState<AppStatus | null>(null);
|
||||||
|
const [hosts, setHosts] = useState<Host[]>([]);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
const refresh = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const [s, h] = await Promise.all([api.getStatus(), api.getHosts()]);
|
||||||
|
setStatus(s);
|
||||||
|
setHosts(h);
|
||||||
|
setError(null);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
setError(e instanceof Error ? e.message : "Backend unreachable");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
refresh();
|
||||||
|
const id = setInterval(refresh, pollMs);
|
||||||
|
return () => clearInterval(id);
|
||||||
|
}, [refresh, pollMs]);
|
||||||
|
|
||||||
|
return { status, hosts, error, loading, refresh };
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue