@@ -4,15 +4,14 @@ import { actionTypes, init, reducer } from "./reducer"
4
4
const noop = ( ) => { }
5
5
6
6
const useAsync = ( arg1 , arg2 ) => {
7
+ const options = typeof arg1 === "function" ? { ...arg2 , promiseFn : arg1 } : arg1
8
+
7
9
const counter = useRef ( 0 )
8
10
const isMounted = useRef ( true )
9
11
const lastArgs = useRef ( undefined )
10
12
const prevOptions = useRef ( undefined )
11
13
const abortController = useRef ( { abort : noop } )
12
14
13
- const options = typeof arg1 === "function" ? { ...arg2 , promiseFn : arg1 } : arg1
14
- const { promise, promiseFn, deferFn, initialValue, onResolve, onReject, watch, watchFn } = options
15
-
16
15
const [ state , dispatch ] = useReducer ( reducer , options , init )
17
16
18
17
const setData = ( data , callback = noop ) => {
@@ -31,11 +30,6 @@ const useAsync = (arg1, arg2) => {
31
30
return error
32
31
}
33
32
34
- const handleResolve = count => data =>
35
- count === counter . current && setData ( data , ( ) => onResolve && onResolve ( data ) )
36
- const handleReject = count => error =>
37
- count === counter . current && setError ( error , ( ) => onReject && onReject ( error ) )
38
-
39
33
const start = ( ) => {
40
34
if ( "AbortController" in window ) {
41
35
abortController . current . abort ( )
@@ -45,12 +39,18 @@ const useAsync = (arg1, arg2) => {
45
39
isMounted . current && dispatch ( { type : actionTypes . start , meta : { counter : counter . current } } )
46
40
}
47
41
42
+ const { onResolve, onReject } = options
43
+ const handleResolve = count => data =>
44
+ count === counter . current && setData ( data , ( ) => onResolve && onResolve ( data ) )
45
+ const handleReject = count => error =>
46
+ count === counter . current && setError ( error , ( ) => onReject && onReject ( error ) )
47
+
48
+ const { promise, promiseFn, initialValue } = options
48
49
const load = ( ) => {
49
50
if ( promise ) {
50
51
start ( )
51
52
return promise . then ( handleResolve ( counter . current ) , handleReject ( counter . current ) )
52
53
}
53
-
54
54
const isPreInitialized = initialValue && counter . current === 0
55
55
if ( promiseFn && ! isPreInitialized ) {
56
56
start ( )
@@ -61,6 +61,7 @@ const useAsync = (arg1, arg2) => {
61
61
}
62
62
}
63
63
64
+ const { deferFn } = options
64
65
const run = ( ...args ) => {
65
66
if ( deferFn ) {
66
67
lastArgs . current = args
@@ -78,6 +79,7 @@ const useAsync = (arg1, arg2) => {
78
79
isMounted . current && dispatch ( { type : actionTypes . cancel , meta : { counter : counter . current } } )
79
80
}
80
81
82
+ const { watch, watchFn } = options
81
83
useEffect ( ( ) => {
82
84
if ( watchFn && prevOptions . current && watchFn ( options , prevOptions . current ) ) load ( )
83
85
} )
0 commit comments