-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
29 lines (25 loc) · 805 Bytes
/
index.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
import { useMemo, useState } from 'react';
export const usePromise = (executorCreator, deps) => {
const executor = useMemo(executorCreator, deps);
const [{ hook, undo }, setMeta] = useState({ hook: {}, undo: null });
const { resolve, reject } = hook;
const wrappedResolve = useMemo(() => () => {
if (typeof undo === 'function') {
undo();
}
resolve();
}, [undo, resolve]);
const wrappedReject = useMemo(() => () => {
if (typeof undo === 'function') {
undo();
}
reject();
}, [undo, reject]);
const promiseCreator = useMemo(() => (...args) => new Promise((re, rj) => {
setMeta({
hook: { resolve: re, reject: rj },
undo: executor(...args),
});
}), [executor, setMeta]);
return [promiseCreator, wrappedResolve, wrappedReject];
};