Skip to content

Commit 7e1e4c5

Browse files
committed
Fix synchronous subscription to addEventListener in useStateEffect hook
1 parent 6341d3c commit 7e1e4c5

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

.core/sdk/named-exports/useDispatcher.js

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
import _ from 'underscore';
22
import op from 'object-path';
3-
import {
4-
ComponentEvent,
5-
useEventEffect,
6-
} from '@atomic-reactor/reactium-sdk-core';
3+
import { ComponentEvent } from '@atomic-reactor/reactium-sdk-core';
74
import cc from 'camelcase';
5+
import { useEffect } from 'react';
86

97
export const useDispatcherFactory = Reactium => ({ props, state }) => (
108
type,
@@ -24,5 +22,25 @@ export const useDispatcherFactory = Reactium => ({ props, state }) => (
2422
if (_.isFunction(cb)) state.removeEventListener(type, cb);
2523
};
2624

27-
export const useStateEffectFactory = Reactium => (handlers = {}, deps) =>
28-
useEventEffect(Reactium.State, handlers, deps);
25+
export const useStateEffectFactory = Reactium => (handlers = {}, deps) => {
26+
const unsubs = [];
27+
const target = Reactium.State;
28+
29+
// sanitize handlers
30+
Object.entries(handlers).forEach(([type, cb]) => {
31+
if (
32+
typeof cb === 'function' &&
33+
!Object.values(op.get(target, ['listeners', type], {})).find(
34+
f => f === cb,
35+
)
36+
) {
37+
unsubs.push(target.addEventListener(type, cb));
38+
}
39+
});
40+
41+
useEffect(() => {
42+
return () => {
43+
unsubs.forEach(unsub => unsub());
44+
};
45+
}, deps);
46+
};

0 commit comments

Comments
 (0)