Skip to content

Fix synchronous subscription to addEventListener in useStateEffect hook #228

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions .core/sdk/named-exports/useDispatcher.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import _ from 'underscore';
import op from 'object-path';
import {
ComponentEvent,
useEventEffect,
} from '@atomic-reactor/reactium-sdk-core';
import { ComponentEvent } from '@atomic-reactor/reactium-sdk-core';
import cc from 'camelcase';
import { useEffect } from 'react';

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

export const useStateEffectFactory = Reactium => (handlers = {}, deps) =>
useEventEffect(Reactium.State, handlers, deps);
export const useStateEffectFactory = Reactium => (handlers = {}, deps) => {
const unsubs = [];
const target = Reactium.State;

// sanitize handlers
Object.entries(handlers).forEach(([type, cb]) => {
if (
typeof cb === 'function' &&
!Object.values(op.get(target, ['listeners', type], {})).find(
f => f === cb,
)
) {
unsubs.push(target.addEventListener(type, cb));
}
});

useEffect(() => {
return () => {
unsubs.forEach(unsub => unsub());
};
}, deps);
};