-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
87 lines (75 loc) · 1.94 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { useEffect, useState, useCallback, useRef } from "react";
type options = {
fn: (...args: any) => Promise<any>;
initialFetch?: boolean;
debug?: boolean;
default?: any;
};
type asyncDataHookArguments = options | Function;
function useAsyncDataHook(options: asyncDataHookArguments, ...rest) {
let fn,
debug = false,
defaultValue = null,
initialFetch = true;
if (typeof options === "function") {
fn = options;
} else {
fn = options.fn;
debug = options.debug ?? false;
initialFetch = options.initialFetch ?? true;
defaultValue = options?.default ?? null;
}
const [args, setArgs] = useState(rest);
const initialFetchRef = useRef(initialFetch);
const [state, setState] = useState({
loading: initialFetch,
error: null,
data: defaultValue,
});
const refetch = useCallback((...newArgs) => {
setArgs(newArgs);
}, []);
const log = debug ? console.log : () => {};
useEffect(() => {
let cancelled = false;
const getData = async () => {
const doneState = {
loading: false,
error: null,
data: null,
};
try {
log("useAsyncDataHook -- fetch", fn.name, ...args);
setState({ ...state, loading: true });
// execute the async function to get data
const data = await fn(...args);
if (!cancelled) {
doneState.data = data;
setState(doneState);
log("useAsyncDataHook -- loaded", data);
}
} catch (e) {
if (!cancelled) {
log("useAsyncDataHook -- error", e);
doneState.error = e;
setState(doneState);
}
}
};
if (initialFetchRef.current) {
getData();
} else {
initialFetchRef.current = true;
}
return () => {
cancelled = true;
};
}, [fn, args]);
return {
data: state.data,
loading: state.loading,
error: state.error,
refetch,
};
}
export default useAsyncDataHook;