Files
linux-cloud-router/web/src/useRead.ts
T

31 lines
906 B
TypeScript

import { useCallback, useEffect, useState } from 'react'
/**
* What load answers, read at once and again by refresh: data, null until the first answer; error, the message of the
* last failure, null after a success; and busy while a read runs. load is read again whenever it changes, so it is
* kept stable, with useCallback where it depends on props.
*/
export function useRead<T>(load: () => Promise<T>) {
const [data, setData] = useState<T | null>(null)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const refresh = useCallback(async () => {
setBusy(true)
try {
setData(await load())
setError(null)
} catch (caught) {
setError((caught as Error).message)
} finally {
setBusy(false)
}
}, [load])
useEffect(() => {
void refresh()
}, [refresh])
return { data, error, busy, refresh }
}