forked from coldemo/gallery.code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseTrigger.ts
More file actions
48 lines (42 loc) · 1.22 KB
/
useTrigger.ts
File metadata and controls
48 lines (42 loc) · 1.22 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
import _ from 'lodash';
import { useEffect, useMemo } from 'react';
type AnyFunc = (...args: any) => any;
interface Options {
debounce?: number;
throttle?: number;
options?: _.DebounceSettings | _.ThrottleSettings;
initial?: boolean;
cancel?: boolean;
singleton?: boolean;
}
export let useTrigger = (options: Options, _func: AnyFunc, deps: any[]) => {
options = options || {};
let func: AnyFunc | (AnyFunc & _.Cancelable) = useMemo(() => {
if (options.debounce) {
return _.debounce(_func, options.debounce, options.options);
} else if (options.throttle) {
return _.throttle(_func, options.throttle, options.options);
} else {
return _func;
}
}, [_func, options.debounce, options.options, options.throttle]);
useEffect(() => {
if (options.singleton) {
if ('cancel' in func) func.cancel();
}
func(...deps);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
useEffect(() => {
if (options.initial) {
if ('cancel' in func) func.cancel();
_func(...deps);
}
return () => {
if (options.cancel) {
if ('cancel' in func) func.cancel();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
};