ConvoyPanel/resources/scripts/util/useDocumentEvent.ts
2022-11-21 06:16:27 +00:00

20 lines
No EOL
581 B
TypeScript

import { useEffect } from 'react'
import { useLatestValue } from './useLatestValue'
export function useDocumentEvent<TType extends keyof DocumentEventMap>(
type: TType,
listener: (ev: DocumentEventMap[TType]) => any,
options?: boolean | AddEventListenerOptions
) {
let listenerRef = useLatestValue(listener)
useEffect(() => {
function handler(event: DocumentEventMap[TType]) {
listenerRef.current(event)
}
document.addEventListener(type, handler, options)
return () => document.removeEventListener(type, handler, options)
}, [type, options])
}