Skip to content

Commit c21a308

Browse files
committed
Allow nullable refs in useEventListener
1 parent 2278328 commit c21a308

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed
Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
/* eslint-disable @typescript-eslint/unified-signatures, @typescript-eslint/no-explicit-any */
2-
import { useEffect, type RefObject } from 'react';
3-
import { unref } from '../../utils/unref/unref.js';
2+
import { useEffect } from 'react';
3+
import { unref, type Unreffable } from '../../utils/unref/unref.js';
44
import { useRefValue } from '../useRefValue/useRefValue.js';
55

6-
export function useEventListener<T extends EventTarget>(
7-
targetOption: RefObject<T> | T | null | undefined,
6+
export function useEventListener<T extends EventTarget | null>(
7+
targetOption: Unreffable<T>,
88
type: string,
99
listener: EventListener,
1010
options?: boolean | AddEventListenerOptions,
@@ -14,14 +14,18 @@ export function useEventListener<T extends EventTarget>(
1414
useEffect(() => {
1515
const target = unref(targetOption);
1616

17+
if (!target) {
18+
return;
19+
}
20+
1721
function callback(this: unknown, event: Event): void {
1822
listenerRef.current?.(event);
1923
}
2024

21-
target?.addEventListener(type, callback, options);
25+
target.addEventListener(type, callback, options);
2226

2327
return () => {
24-
target?.removeEventListener(type, callback, options);
28+
target.removeEventListener(type, callback, options);
2529
};
2630
}, [listenerRef, options, targetOption, type]);
2731
}

0 commit comments

Comments
 (0)