Files
misode.github.io/src/app/hooks/useAsync.ts
2022-06-16 00:58:14 +02:00

22 lines
589 B
TypeScript

import type { Inputs } from 'preact/hooks'
import { useEffect } from 'preact/hooks'
import type { AsyncCancel, AsyncState } from './index.js'
import { useAsyncFn } from './index.js'
export function useAsync<R>(
fn: () => Promise<R | typeof AsyncCancel>,
inputs: Inputs = [],
initialState: AsyncState<R> = { loading: true },
): AsyncState<R> & { refresh: () => Promise<unknown> } {
const [state, callback] = useAsyncFn<R, () => Promise<R | typeof AsyncCancel>>(fn, inputs, initialState)
useEffect(() => {
callback()
}, [callback])
return {
...state,
refresh: callback,
}
}