File size: 1,759 Bytes
1c34a81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { useCallback, useEffect, useState } from 'react'
import { useApi } from './ApiProvider'

export type ApiQueryState<T> = {
  data: T | null
  error: Error | null
  loading: boolean
  refetch: () => void
}

export function useApiQuery<T>(path: string | null, pollIntervalMs = 0): ApiQueryState<T> {
  const { request } = useApi()
  const [data, setData] = useState<T | null>(null)
  const [error, setError] = useState<Error | null>(null)
  const [loading, setLoading] = useState(Boolean(path))
  const [revision, setRevision] = useState(0)
  const refetch = useCallback(() => setRevision(value => value + 1), [])

  useEffect(() => {
    if (!path) {
      setData(null)
      setError(null)
      setLoading(false)
      return
    }
    const controller = new AbortController()
    let pollTimer: number | undefined
    let disposed = false
    setLoading(current => current || data === null)
    setError(null)
    const load = async () => {
      try {
        const next = await request<T>(path, { signal: controller.signal })
        if (disposed) return
        setData(next)
        setError(null)
      } catch (caught) {
        if (disposed || controller.signal.aborted) return
        setError(caught instanceof Error ? caught : new Error('Backend request failed.'))
      } finally {
        if (disposed) return
        setLoading(false)
        if (pollIntervalMs > 0) pollTimer = window.setTimeout(load, pollIntervalMs)
      }
    }
    void load()
    return () => {
      disposed = true
      controller.abort()
      if (pollTimer !== undefined) window.clearTimeout(pollTimer)
    }
  }, [request, path, pollIntervalMs, revision])

  return { data, error, loading, refetch }
}