Skip to content

Commit 71af0a2

Browse files
committed
fix: prevent keyboard handlers stack mutation during iteration
1 parent fdea3a9 commit 71af0a2

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

src/hooks/useGlobalKey.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { useEffect } from "react";
21
import { sendGTMEvent } from "@next/third-parties/google";
2+
import { useEffect } from "react";
33

44
type KeyboardKey = KeyboardEvent["key"];
55

@@ -28,7 +28,7 @@ export function useGlobalKeyCallback() {
2828
if (!(lowerKey in allHandlersStacks)) return;
2929
if (shouldHandleAsNativeEvent(event)) return;
3030
const handlersStack = allHandlersStacks[lowerKey];
31-
for (let handler of handlersStack.reverse()) {
31+
for (let handler of [...handlersStack].reverse()) {
3232
if (handler()) {
3333
event.preventDefault();
3434
event.stopPropagation();
@@ -63,7 +63,9 @@ export const useCallbackOnKey = ({
6363
return () => {
6464
if (!isDisabled) {
6565
const index = allHandlersStacks[lowerKey].indexOf(handler);
66-
allHandlersStacks[lowerKey].splice(index, 1);
66+
if (index > -1) {
67+
allHandlersStacks[lowerKey].splice(index, 1);
68+
}
6769
}
6870
};
6971
}, [key, handler, isDisabled]);

0 commit comments

Comments
 (0)