Skip to content

Commit

Permalink
useEventListener hook
Browse files Browse the repository at this point in the history
  • Loading branch information
luludotdev committed Dec 6, 2023
1 parent 5693e3e commit 212bc8e
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/react/hooks/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,29 @@ import type {
ClientEvents,
CommonEvents,
Event,
EventEmitter,
EventHandler,
} from '@dreamlab.gg/core/events'
import { useEffect } from 'https://esm.sh/v136/[email protected]'
import { useGame } from './useGame.ts'

export const useEventListener = <
EventTypes extends EventEmitter.ValidEventTypes,
T extends EventEmitter.EventNames<EventTypes>,
>(
emitter: EventEmitter<EventTypes>,
event: T,
handler: EventEmitter.EventListener<EventTypes, T>,
): void => {
useEffect(() => {
emitter.addListener(event, handler)

return () => {
emitter.removeListener(event, handler)
}
}, [emitter, event, handler])
}

export const useClientEventListener = <T extends Event<ClientEvents>>(
event: T,
handler: EventHandler<T, ClientEvents>,
Expand Down

0 comments on commit 212bc8e

Please sign in to comment.