-
Notifications
You must be signed in to change notification settings - Fork 0
/
asyncAction.ts
56 lines (47 loc) · 1.15 KB
/
asyncAction.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { createSignal } from 'solid-js';
import { makePlugin } from '~/api';
export function withAsyncAction() {
return makePlugin(
() => {
return {
asyncAction<P, R>(doSomething: (payload: P) => Promise<R>) {
return makeAsyncAction(doSomething);
},
};
},
{ name: 'asyncAction' },
);
}
export interface AsyncAction<T, R> {
(payload: T): void;
(payload?: void): void;
loading: boolean;
latestValue(): R | undefined;
}
export function makeAsyncAction<T, R = void>(
effectGeneratorCallback: (data: T) => Promise<R>,
): AsyncAction<T, R> {
const [loading, setLoading] = createSignal<boolean>(false);
const [latestValue, setLatestValue] = createSignal<R>();
function notify(state?: T | void) {
setLoading(true);
effectGeneratorCallback(state as T)
.then((result) => {
setLatestValue(() => result);
})
.finally(() => setLoading(false));
}
Object.defineProperties(notify, {
loading: {
get() {
return loading();
},
},
latestValue: {
get() {
return latestValue();
},
},
});
return notify as AsyncAction<T, R>;
}