lama / lama_cleaner /app /src /hooks /useAsyncMemo.tsx
LinHanjiang's picture
Upload 259 files
74aacd5
raw
history blame contribute delete
766 Bytes
import { DependencyList, useEffect, useState } from 'react'
export function useAsyncMemo<T>(
factory: () => Promise<T> | undefined | null,
deps: DependencyList
): T | undefined
export function useAsyncMemo<T>(
factory: () => Promise<T> | undefined | null,
deps: DependencyList,
initial: T
): T
export function useAsyncMemo<T>(
factory: () => Promise<T> | undefined | null,
deps: DependencyList,
initial?: T
) {
const [val, setVal] = useState<T | undefined>(initial)
useEffect(() => {
let cancel = false
const promise = factory()
if (promise === undefined || promise === null) return
promise.then(v => {
if (!cancel) {
setVal(v)
}
})
return () => {
cancel = true
}
}, deps)
return val
}