Created
February 7, 2024 14:25
-
-
Save RStankov/93e49fb43b9043e7ff7be715185626eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import mitt from 'mitt'; | |
interface IEventsMap { | |
modalOpen: { | |
content: React.ReactNode; | |
url?: string; | |
}; | |
modalClose: null; | |
commentCreated: { | |
id: string; | |
}; | |
} | |
type IEventArguments<T extends keyof IEventsMap> = null extends IEventsMap[T] | |
? [] | |
: [IEventsMap[T]]; | |
const eventBus = mitt() as { | |
emit<T extends keyof IEventsMap>(e: T, ...p: IEventArguments<T>): void; | |
on<T extends keyof IEventsMap>( | |
e: T, | |
f: (...p: IEventArguments<T>) => void, | |
): void; | |
off<T extends keyof IEventsMap>( | |
e: T, | |
f: (...p: IEventArguments<T>) => void, | |
): void; | |
}; | |
export function emit<T extends keyof IEventsMap>( | |
event: T, | |
...payload: IEventArguments<T> | |
) { | |
if (typeof window !== 'undefined') { | |
eventBus.emit(event, ...payload); | |
} else { | |
console.warn('emit called on server'); | |
} | |
} | |
export function useEventBus<T extends keyof IEventsMap>( | |
eventName: T, | |
handler: (...payload: IEventArguments<T>) => void, | |
) { | |
React.useEffect(() => { | |
eventBus.on(eventName, handler); | |
return () => eventBus.off(eventName, handler); | |
}, [eventName, handler]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is code companion from my post EventBus in React Applications