generated from adamrybinski/haunted-snow
-
Notifications
You must be signed in to change notification settings - Fork 1
/
useEffectActions.js
77 lines (66 loc) · 1.85 KB
/
useEffectActions.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { useEffect, useRef, useLayoutEffect } from './deps.js';
import { partition } from './utils.js';
export function useEffectActions(service) {
const effectActionsRef = useRef([]);
const layoutEffectActionsRef = useRef([]);
useLayoutEffect(() => {
const sub = service.subscribe((currentState) => {
if (currentState.actions.length) {
const reactEffectActions = currentState.actions.filter(
(action) => {
return (
typeof action.exec === 'function' &&
'__effect' in (action).exec
);
}
);
const [effectActions, layoutEffectActions] = partition(
reactEffectActions,
(action) => {
return action.exec.__effect === ReactEffectType.Effect;
}
);
effectActionsRef.current.push(
...effectActions.map(
(effectAction) => [effectAction, currentState]
)
);
layoutEffectActionsRef.current.push(
...layoutEffectActions.map(
(layoutEffectAction) => [layoutEffectAction, currentState]
)
);
}
});
return () => {
sub.unsubscribe();
};
}, []);
useLayoutEffect(() => {
while (layoutEffectActionsRef.current.length) {
const [
layoutEffectAction,
effectState
] = layoutEffectActionsRef.current.shift();
executeEffect(layoutEffectAction, effectState);
}
});
useEffect(() => {
while (effectActionsRef.current.length) {
const [effectAction, effectState] = effectActionsRef.current.shift();
executeEffect(effectAction, effectState);
}
});
}
function executeEffect(
action,
state
) {
const { exec } = action;
const originalExec = exec(state.context, state._event.data, {
action,
state,
_event: state._event
});
originalExec();
}