-
Notifications
You must be signed in to change notification settings - Fork 0
/
useDebounce.js
66 lines (66 loc) · 1.83 KB
/
useDebounce.js
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
import { useCallback, useRef } from "react";
import "@babel/polyfill";
export default (
fn,
delay = 0,
promise,
dontFireOnbackspace,
lengthConstraint,
event
) => {
const ref = useRef({});
ref.current.fn = fn;
ref.current.key = event.key;
= ref.current.lengthConstraint = lengthConstraint;
return useCallback(
(...args) => {
if (ref.current.timeout) {
clearTimeout(ref.current.timeout);
}
if (promise) {
ref.current.promise = new Promise((resolve, reject) => {
ref.current.resolve = resolve;
ref.current.reject = reject;
});
}
ref.current.timeout = setTimeout(async () => {
ref.current.timeout = undefined;
const checkValueLength = () => {
if (lengthConstraint) {
return args[0].length > lengthConstraint;
} else {
return true;
}
};
const checkKey = () => {
if (dontFireOnbackspace) {
if (ref.current.key === "Backspace") {
return false;
} else {
return true;
}
} else {
return true;
}
};
try {
if (!promise && checkValueLength() && checkKey()) {
const response = ref.current.fn(...args);
ref.current.response = response;
} else if (promise && checkValueLength() && checkKey()) {
const response = await ref.current.fn(...args);
ref.current.resolve(response);
}
} catch (err) {
if (!promise && checkValueLength()) {
throw new Error(err);
} else if (promise && checkValueLength()) {
ref.current.reject(err);
}
}
}, delay);
return promise ? ref.current.promise : ref.current.response;
},
[delay]
);
};