| import { useEffect, useState } from "react"; |
| import { API_BASE } from "../api/client"; |
|
|
| interface ActiveSession { |
| client_id: string; |
| last_seen: string; |
| } |
|
|
| interface ActiveSessionsResult { |
| count: number; |
| sessions: ActiveSession[]; |
| loading: boolean; |
| } |
|
|
| export function useActiveSessions(intervalMs = 30_000): ActiveSessionsResult { |
| const [count, setCount] = useState(0); |
| const [sessions, setSessions] = useState<ActiveSession[]>([]); |
| const [loading, setLoading] = useState(true); |
|
|
| useEffect(() => { |
| let cancelled = false; |
|
|
| async function fetch_() { |
| try { |
| const res = await fetch(`${API_BASE}/api/active-sessions`); |
| if (!res.ok || cancelled) return; |
| const data = await res.json(); |
| setCount(data.count ?? 0); |
| setSessions(data.active_sessions ?? []); |
| } catch { |
| |
| } finally { |
| if (!cancelled) setLoading(false); |
| } |
| } |
|
|
| fetch_(); |
| const id = window.setInterval(fetch_, intervalMs); |
| return () => { |
| cancelled = true; |
| clearInterval(id); |
| }; |
| }, [intervalMs]); |
|
|
| return { count, sessions, loading }; |
| } |
|
|