Skip to content

Commit

Permalink
[@mantine/utils] Fix custom events not firing in strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
rtivital committed Aug 12, 2022
1 parent 5fcd65b commit 7aa413f
Showing 1 changed file with 10 additions and 13 deletions.
@@ -1,9 +1,11 @@
import { useEffect, useMemo } from 'react';
import { useEffect, useLayoutEffect } from 'react';

function dispatchEvent<T>(type: string, detail?: T) {
window.dispatchEvent(new CustomEvent(type, { detail }));
}

const useIsomorphicEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;

export function createUseExternalEvents<Handlers extends Record<string, (detail: any) => void>>(
prefix: string
) {
Expand All @@ -13,22 +15,17 @@ export function createUseExternalEvents<Handlers extends Record<string, (detail:
return acc;
}, {});

useMemo(() => {
if (typeof window !== 'undefined') {
useIsomorphicEffect(() => {
Object.keys(handlers).forEach((eventKey) => {
window.removeEventListener(eventKey, handlers[eventKey]);
window.addEventListener(eventKey, handlers[eventKey]);
});

return () =>
Object.keys(handlers).forEach((eventKey) => {
window.removeEventListener(eventKey, handlers[eventKey]);
window.addEventListener(eventKey, handlers[eventKey]);
});
}
}, []);

useEffect(
() => () =>
Object.keys(handlers).forEach((eventKey) => {
window.removeEventListener(eventKey, handlers[eventKey]);
}),
[]
);
}

function createEvent<EventKey extends keyof Handlers>(event: EventKey) {
Expand Down

0 comments on commit 7aa413f

Please sign in to comment.