Skip to content

Instantly share code, notes, and snippets.

@domanskyi
Created May 27, 2024 12:10
Show Gist options
  • Save domanskyi/0de112bce9672cf7c85478aadc1525c0 to your computer and use it in GitHub Desktop.
Save domanskyi/0de112bce9672cf7c85478aadc1525c0 to your computer and use it in GitHub Desktop.
Simple React hook to propagade events to the parent componets using native events API
import { useCallback, useEffect } from 'react';
type TUseCustomEventListenerRes = {
dispatchEvent: (data: CustomEventInit) => void;
};
/**
* @name dispatchGlobalEvent
* @param {String} eventName The name of the event to dispatch
* @param {Array} meta Any optional data to pass to the event
* @see credit: https://gist.github.com/jamestowers/40646b505167d88406c1de647ffa3885
*/
const dispatchGlobalEvent = (eventName: string, meta?: CustomEventInit): void => {
// Compatible with IE
// @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work
let event;
if (typeof window?.CustomEvent === 'function') {
event = new window.CustomEvent(eventName, { detail: meta });
} else {
event = document.createEvent('Event');
event.initEvent(eventName, false, true);
event.detail = meta;
}
window?.dispatchEvent(event);
};
/**
* @param {String} name - The name of the event to listen to
* @param onDispatch - Callback to execute when the logout is triggered
* @returns {Object} - Object with the dispatchEvent func that triggers the logout event
* Utility to dispatch and listen on custom **user logout** event.
* Allows to listen when the logout event is triggered from any part of the application.
*/
const useCustomEventListener = (eventName: string, onDispatch?: () => void): TUseCustomEventListenerRes => {
const dispatchEvent = useCallback(
(data?: CustomEventInit) => {
dispatchGlobalEvent(eventName, data);
},
[eventName],
);
useEffect(() => {
if (onDispatch) {
window?.addEventListener(eventName, onDispatch);
return () => {
window?.removeEventListener(eventName, onDispatch);
};
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { dispatchEvent };
};
export default useCustomEventListener;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment