Skip to content

Commit 896a05f

Browse files
committed
Create variables just-in-time.
1 parent 2b7381d commit 896a05f

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

src/useAsync.js

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,14 @@ import { actionTypes, init, reducer } from "./reducer"
44
const noop = () => {}
55

66
const useAsync = (arg1, arg2) => {
7+
const options = typeof arg1 === "function" ? { ...arg2, promiseFn: arg1 } : arg1
8+
79
const counter = useRef(0)
810
const isMounted = useRef(true)
911
const lastArgs = useRef(undefined)
1012
const prevOptions = useRef(undefined)
1113
const abortController = useRef({ abort: noop })
1214

13-
const options = typeof arg1 === "function" ? { ...arg2, promiseFn: arg1 } : arg1
14-
const { promise, promiseFn, deferFn, initialValue, onResolve, onReject, watch, watchFn } = options
15-
1615
const [state, dispatch] = useReducer(reducer, options, init)
1716

1817
const setData = (data, callback = noop) => {
@@ -31,11 +30,6 @@ const useAsync = (arg1, arg2) => {
3130
return error
3231
}
3332

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-
3933
const start = () => {
4034
if ("AbortController" in window) {
4135
abortController.current.abort()
@@ -45,12 +39,18 @@ const useAsync = (arg1, arg2) => {
4539
isMounted.current && dispatch({ type: actionTypes.start, meta: { counter: counter.current } })
4640
}
4741

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
4849
const load = () => {
4950
if (promise) {
5051
start()
5152
return promise.then(handleResolve(counter.current), handleReject(counter.current))
5253
}
53-
5454
const isPreInitialized = initialValue && counter.current === 0
5555
if (promiseFn && !isPreInitialized) {
5656
start()
@@ -61,6 +61,7 @@ const useAsync = (arg1, arg2) => {
6161
}
6262
}
6363

64+
const { deferFn } = options
6465
const run = (...args) => {
6566
if (deferFn) {
6667
lastArgs.current = args
@@ -78,6 +79,7 @@ const useAsync = (arg1, arg2) => {
7879
isMounted.current && dispatch({ type: actionTypes.cancel, meta: { counter: counter.current } })
7980
}
8081

82+
const { watch, watchFn } = options
8183
useEffect(() => {
8284
if (watchFn && prevOptions.current && watchFn(options, prevOptions.current)) load()
8385
})

0 commit comments

Comments
 (0)