2022-04-08 07:00:46 -04:00
|
|
|
import * as React from 'react'
|
|
|
|
import useSafeDispatch from './use-safe-dispatch'
|
|
|
|
import { Nullable } from '../../../../types/utils'
|
|
|
|
|
2022-05-18 09:46:18 -04:00
|
|
|
type State<T> = {
|
2022-04-08 07:00:46 -04:00
|
|
|
status: 'idle' | 'pending' | 'resolved' | 'rejected'
|
2022-05-18 09:46:18 -04:00
|
|
|
data: Nullable<T>
|
|
|
|
error: Nullable<Error>
|
2022-04-08 07:00:46 -04:00
|
|
|
}
|
2022-05-18 09:46:18 -04:00
|
|
|
type Action<T> = Partial<State<T>>
|
2022-04-08 07:00:46 -04:00
|
|
|
|
2022-05-18 09:46:18 -04:00
|
|
|
const defaultInitialState: State<null> = {
|
|
|
|
status: 'idle',
|
|
|
|
data: null,
|
|
|
|
error: null,
|
|
|
|
}
|
2022-04-08 07:00:46 -04:00
|
|
|
|
2022-05-18 09:46:18 -04:00
|
|
|
function useAsync<T = any>(initialState?: Partial<State<T>>) {
|
2022-04-22 09:49:26 -04:00
|
|
|
const initialStateRef = React.useRef({
|
|
|
|
...defaultInitialState,
|
|
|
|
...initialState,
|
|
|
|
})
|
2022-04-08 07:00:46 -04:00
|
|
|
const [{ status, data, error }, setState] = React.useReducer(
|
2022-05-18 09:46:18 -04:00
|
|
|
(state: State<T>, action: Action<T>) => ({ ...state, ...action }),
|
2022-04-22 09:49:26 -04:00
|
|
|
initialStateRef.current
|
2022-04-08 07:00:46 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
const safeSetState = useSafeDispatch(setState)
|
|
|
|
|
|
|
|
const setData = React.useCallback(
|
2022-05-18 09:46:18 -04:00
|
|
|
(data: Nullable<T>) => safeSetState({ data, status: 'resolved' }),
|
2022-04-08 07:00:46 -04:00
|
|
|
[safeSetState]
|
|
|
|
)
|
|
|
|
|
|
|
|
const setError = React.useCallback(
|
2022-05-18 09:46:18 -04:00
|
|
|
(error: Nullable<Error>) => safeSetState({ error, status: 'rejected' }),
|
2022-04-08 07:00:46 -04:00
|
|
|
[safeSetState]
|
|
|
|
)
|
|
|
|
|
2022-04-22 09:49:26 -04:00
|
|
|
const reset = React.useCallback(
|
|
|
|
() => safeSetState(initialStateRef.current),
|
|
|
|
[safeSetState]
|
|
|
|
)
|
|
|
|
|
2022-04-08 07:00:46 -04:00
|
|
|
const runAsync = React.useCallback(
|
2022-05-18 09:46:18 -04:00
|
|
|
(promise: Promise<T>) => {
|
2022-04-08 07:00:46 -04:00
|
|
|
safeSetState({ status: 'pending' })
|
|
|
|
|
2022-04-22 09:49:26 -04:00
|
|
|
return promise.then(
|
|
|
|
data => {
|
|
|
|
setData(data)
|
|
|
|
return data
|
|
|
|
},
|
|
|
|
error => {
|
|
|
|
setError(error)
|
|
|
|
return Promise.reject(error)
|
|
|
|
}
|
|
|
|
)
|
2022-04-08 07:00:46 -04:00
|
|
|
},
|
|
|
|
[safeSetState, setData, setError]
|
|
|
|
)
|
|
|
|
|
|
|
|
return {
|
|
|
|
isIdle: status === 'idle',
|
|
|
|
isLoading: status === 'pending',
|
|
|
|
isError: status === 'rejected',
|
|
|
|
isSuccess: status === 'resolved',
|
|
|
|
setData,
|
|
|
|
setError,
|
|
|
|
error,
|
|
|
|
status,
|
|
|
|
data,
|
|
|
|
runAsync,
|
2022-04-22 09:49:26 -04:00
|
|
|
reset,
|
2022-04-08 07:00:46 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default useAsync
|
|
|
|
export type UseAsyncReturnType = ReturnType<typeof useAsync>
|