brf/client/shared/hooks/use_promise.ts

18 lines
511 B
TypeScript

import { useRef, useState } from 'preact/hooks'
export default function usePromise<R = any, E = Error>(fn: () => Promise<R>) {
const [result, setResult] = useState<R | null>(null)
const [error, setError] = useState<E | null>(null)
const promiseRef = useRef<Promise<void> | null>(null)
if (!promiseRef.current) {
throw (promiseRef.current = fn().then(setResult, setError))
} else if (result) {
return result
} else if (error) {
throw error
} else {
throw promiseRef.current
}
}