quasvel
Version:
Access and interact with Aragon Organizations and their apps.
41 lines (34 loc) • 863 B
text/typescript
import { useEffect, useState } from 'react'
export function useCancellableAsync<Result>(
asyncCall: (stop: () => void) => Promise<Result | undefined>,
deps: any[]
): [Result, boolean] {
const [result, setResult] = useState<Result | undefined>(undefined)
const [loading, setLoading] = useState<boolean>(true)
useEffect(() => {
let cancelled = false
const cancel = () => {
cancelled = true
}
const stop = () => {
cancelled = true
setLoading(false)
}
setLoading(true)
asyncCall(stop)
.then((result) => {
if (!cancelled) {
setResult(result)
setLoading(false)
}
})
.catch(() => {
if (!cancelled) {
setResult(undefined)
setLoading(false)
}
})
return cancel
}, deps)
return [result as Result, loading]
}