Skip to content

Commit

Permalink
Fixed double execution of callback when options is passed
Browse files Browse the repository at this point in the history
  • Loading branch information
JohannesKlauss committed Jun 18, 2021
1 parent 3d1ffaf commit fd55014
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
20 changes: 17 additions & 3 deletions docs/useHotkeys.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ edits the field content.
<div>
{amount >= 0 ? 'Add' : 'Remove'} {Math.abs(amount)} dollars {amount >= 0 ? 'from' : 'to'} my bank account.
</div>
<div contentEditable={true}>Edit this text.</div>
<div contentEditable={true} suppressContentEditableWarning={true}>Edit this text.</div>
</>
);
}}
Expand All @@ -167,12 +167,26 @@ If you want to have hotkeys active while a user edits a tags contents you can pa
<div>
{amount >= 0 ? 'Add' : 'Remove'} {Math.abs(amount)} dollars {amount >= 0 ? 'from' : 'to'} my bank account.
</div>
<div contentEditable={true}>Edit this text.</div>
<div contentEditable={true} suppressContentEditableWarning={true}>Edit this text.</div>
</>
);
}}
</Playground>

## Using arrow keys

To use arrow keys,
To use arrow keys, please use `left`, `right`, `up` and `down` as the identifiers for the arrows, like so:

<Playground>
{() => {
const [amount, setAmount] = useState(0);
useHotkeys('shift-right', () => setAmount(prevAmount => prevAmount + 100), {splitKey: '-'});
return (
<>
<div>
Add {amount} dollars to my bank account.
</div>
</>
);
}}
</Playground>
4 changes: 4 additions & 0 deletions src/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ test('useHotkeys should use correctly assign options and deps argument when usin
userEvent.keyboard('{Shift>}A{/Shift}');

expect(callback).toHaveBeenCalledTimes(2);

userEvent.keyboard('{Shift>}A{/Shift}');

expect(callback).toHaveBeenCalledTimes(3);
});

test('useHotkeys should only trigger once if neither keyup nor keydown are set', () => {
Expand Down
7 changes: 5 additions & 2 deletions src/useHotkeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export function useHotkeys<T extends Element>(keys: string, callback: KeyHandler
enabled = true,
enableOnContentEditable = false,
} = options as Options || {};

const ref = useRef<T | null>(null);

// The return value of this callback determines if the browsers default behavior is prevented.
Expand Down Expand Up @@ -82,8 +83,10 @@ export function useHotkeys<T extends Element>(keys: string, callback: KeyHandler

hotkeys(keys, (options as Options) || {}, memoisedCallback);

return () => hotkeys.unbind(keys, memoisedCallback);
}, [memoisedCallback, options, keys, enabled]);
return () => {
hotkeys.unbind(keys, memoisedCallback)
};
}, [memoisedCallback, keys, enabled]);

return ref;
}

0 comments on commit fd55014

Please sign in to comment.