import { useEffect, useRef } from 'react'; import { eventBus, type EventMap } from '../utils/eventBus'; type EventListener = { busEventKey: K; action: (data: EventMap[K]) => void; }; /** * Hook to listen to events from the EventBus * Automatically subscribes on mount and unsubscribes on unmount */ export const useEventListener = (listener: EventListener) => { const actionRef = useRef(listener.action); // Keep action ref up to date useEffect(() => { actionRef.current = listener.action; }, [listener.action]); useEffect(() => { // Subscribe to the event const unsubscribe = eventBus.on(listener.busEventKey, (data) => { actionRef.current(data); }); // Cleanup: unsubscribe when component unmounts return unsubscribe; }, [listener.busEventKey]); };