Skip to content

Commit

Permalink
fix: useKeyMap unmount removes keys (3778)
Browse files Browse the repository at this point in the history
  • Loading branch information
patomation committed Sep 22, 2024
1 parent e7915d8 commit f91730f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
30 changes: 30 additions & 0 deletions packages/graphiql-react/src/editor/__tests__/hooks.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { renderHook } from '@testing-library/react';
import { useKeyMap } from '../hooks';
import { CodeMirrorEditor, KeyMap } from '../types';

describe('hooks', () => {
describe('useKeyMap', () => {
it('works correctly', () => {
let keys = {};
const editor: Pick<CodeMirrorEditor, 'addKeyMap' | 'removeKeyMap'> = {
addKeyMap: jest.fn((keyMap: KeyMap) => {
keys = { ...keys, ...keyMap };
}),
removeKeyMap: jest.fn(key => {
delete keys[key];
}),
};
const callback = jest.fn();
const { unmount } = renderHook(() =>
useKeyMap(
editor as unknown as CodeMirrorEditor,
['foo', 'bar'],
callback,
),
);
expect(Object.keys(keys).length).toBe(2);
unmount();
expect(Object.keys(keys).length).toBe(0);
});
});
});
10 changes: 7 additions & 3 deletions packages/graphiql-react/src/editor/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,12 @@ export function useKeyMap(
if (!editor) {
return;
}
for (const key of keys) {
editor.removeKeyMap(key);
}
const handleRemoveKeys = () => {
for (const key of keys) {
editor.removeKeyMap(key);
}
};
handleRemoveKeys();

if (callback) {
const keyMap: Record<string, EmptyCallback> = {};
Expand All @@ -147,6 +150,7 @@ export function useKeyMap(
}
editor.addKeyMap(keyMap);
}
return handleRemoveKeys;
}, [editor, keys, callback]);
}

Expand Down

0 comments on commit f91730f

Please sign in to comment.