-
Notifications
You must be signed in to change notification settings - Fork 3k
/
useSingleExecution.js
40 lines (34 loc) · 1.14 KB
/
useSingleExecution.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
import {InteractionManager} from 'react-native';
import {useCallback, useState, useRef} from 'react';
/**
* With any action passed in, it will only allow 1 such action to occur at a time.
*
* @returns {Object}
*/
export default function useSingleExecution() {
const [isExecuting, setIsExecuting] = useState(false);
const isExecutingRef = useRef();
isExecutingRef.current = isExecuting;
const singleExecution = useCallback(
(action) =>
(...params) => {
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};
}