dsh-brain/src-client/panel/useApi.ts

53 lines
1.8 KiB
TypeScript

// Small data-loading state machine shared by the Brain panel tabs.
import * as React from 'react'
import { messageOf } from '../api'
export type ApiStatus = 'idle' | 'loading' | 'ready' | 'error'
export interface ApiState<T> {
status: ApiStatus
data: T | null
error: string | null
}
export interface UseApiOptions {
/** false pauses all loading and polling (used by better-sidebar visible=false). */
visible?: boolean
/** Optional polling interval in milliseconds. */
pollMs?: number
/** Extra dependencies that should trigger a reload. */
deps?: unknown[]
}
export function useApi<T>(loader: () => Promise<T>, options: UseApiOptions = {}): ApiState<T> & { reload: () => void; mutate: (data: T | null) => void } {
const visible = options.visible !== false
const loaderRef = React.useRef(loader)
loaderRef.current = loader
const [state, setState] = React.useState<ApiState<T>>({ status: 'idle', data: null, error: null })
const reload = React.useCallback((): void => {
if (!visible) return
setState((previous) => ({ status: previous.data === null ? 'loading' : 'ready', data: previous.data, error: null }))
loaderRef.current().then(
(data) => setState({ status: 'ready', data, error: null }),
(failure) => setState((previous) => ({ status: 'error', data: previous.data, error: messageOf(failure) })),
)
}, [visible])
const dependencies = options.deps ?? []
React.useEffect(() => {
if (!visible) return
reload()
if (options.pollMs === undefined) return
const timer = setInterval(reload, options.pollMs)
return () => clearInterval(timer)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible, options.pollMs, reload, ...dependencies])
return {
...state,
reload,
mutate: (data: T | null) => setState({ status: data === null ? 'idle' : 'ready', data, error: null }),
}
}