-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
94 lines (77 loc) · 1.98 KB
/
index.ts
File metadata and controls
94 lines (77 loc) · 1.98 KB
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
88
89
90
91
92
93
94
import { useEffect, useRef, useState } from "react";
// useRemount Hook
export const useRemount = (dependencies: any[] = []) => {
const [key, setKey] = useState(Math.random());
useEffect(() => {
setKey(Math.random());
}, dependencies);
return {
key,
remount: () => setKey(Math.random())
};
};
// usePrevious Hook
export const usePrevious = <T>(value: T): T | undefined => {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
// useTimeout Hook
export const useTimeout = (callback: () => void, delay: number) => {
useEffect(() => {
const timer = setTimeout(callback, delay);
return () => clearTimeout(timer);
}, [callback, delay]);
};
// useInterval Hook
export const useInterval = (callback: () => void, delay: number) => {
const savedCallback = useRef<() => void>();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (delay !== null) {
const tick = () => {
if (savedCallback.current) {
savedCallback.current();
}
};
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};
// useRequest Hook
export const useRequest = (requestFunction: () => Promise<any>, dependencies: any[] = []) => {
const [data, setData] = useState<any>(null);
const [error, setError] = useState<any>(null);
const [loading, setLoading] = useState<boolean>(false);
const fetchData = async () => {
setLoading(true);
try {
const result = await requestFunction();
setData(result);
setError(null);
} catch (err) {
setError(err);
setData(null);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, dependencies);
return { data, error, loading, retry: fetchData };
};
// Exporting all hooks
const SuperReact = {
useRemount,
usePrevious,
useTimeout,
useInterval,
useRequest
};
export default SuperReact;