x
This commit is contained in:
38
frontend/src/hooks/useEVSessions.ts
Normal file
38
frontend/src/hooks/useEVSessions.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { getActiveEvSessions, type ActiveEvSessionRow } from '../api/backend'
|
||||
|
||||
const POLL_MS = 30_000
|
||||
|
||||
export function useEVSessions(siteId: number | null) {
|
||||
const [sessions, setSessions] = useState<ActiveEvSessionRow[]>([])
|
||||
const [ready, setReady] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (siteId == null) {
|
||||
setSessions([])
|
||||
setReady(true)
|
||||
return
|
||||
}
|
||||
try {
|
||||
const rows = await getActiveEvSessions(siteId)
|
||||
setSessions(rows)
|
||||
setError(null)
|
||||
} catch {
|
||||
setSessions([])
|
||||
setError('EV session se nepodařilo načíst')
|
||||
} finally {
|
||||
setReady(true)
|
||||
}
|
||||
}, [siteId])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
if (siteId == null) return
|
||||
const id = window.setInterval(() => void load(), POLL_MS)
|
||||
return () => window.clearInterval(id)
|
||||
}, [load, siteId])
|
||||
|
||||
return { sessions, ready, error, reload: load }
|
||||
}
|
||||
Reference in New Issue
Block a user