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(load: () => Promise) { const [data, setData] = useState(null) const [error, setError] = useState(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 } }