-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathindex.native.ts
40 lines (33 loc) · 1.23 KB
/
index.native.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
import {useCallback, useRef, useState} from 'react';
import {InteractionManager} from 'react-native';
type Action<T extends unknown[]> = (...params: T) => void | Promise<void>;
/**
* With any action passed in, it will only allow 1 such action to occur at a time.
*/
export default function useSingleExecution() {
const [isExecuting, setIsExecuting] = useState(false);
const isExecutingRef = useRef<boolean>();
isExecutingRef.current = isExecuting;
const singleExecution = useCallback(
<T extends unknown[]>(action: Action<T>) =>
(...params: T) => {
if (isExecutingRef.current) {
return;
}
setIsExecuting(true);
isExecutingRef.current = true;
const execution = action(...params);
InteractionManager.runAfterInteractions(() => {
if (!(execution instanceof Promise)) {
setIsExecuting(false);
return;
}
execution.finally(() => {
setIsExecuting(false);
});
});
},
[],
);
return {isExecuting, singleExecution};
}