Skip to content

BUG | useMagicKeys | KeyboardEvent "keyup" with empty string key causes unhandled errors #5148

@dwjohnston

Description

@dwjohnston

Describe the bug

If a keyboard event with an empty string key is emitted, this will cause vueuse to emit an unhandled error like so:

@vueuse_core.js?v=6d583e30:5298 Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase')
    at clearDeps (@vueuse_core.js?v=6d583e30:5298:34)
    at updateRefs (@vueuse_core.js?v=6d583e30:5322:5)
    at useEventListener.passive.passive (@vueuse_core.js?v=6d583e30:5336:5)
    at <anonymous>:1:8

The default value for a KeyboardEvent's key is the empty string.

The issue was introduced here:

https://github.com/vueuse/vueuse/pull/5037/files#diff-e61b847471f6438ac5f4f549d85ef7d5d6aa045bdcca27640287bd60e6640007R124

where key[0].toUpperCase() if key is "" resolves to undefined.toUpperCase()

Reproduction

https://github.com/dwjohnston/vue-use-bug-use-magic-keys

<script setup lang="ts">
import { useMagicKeys } from "@vueuse/core";
import { watch } from "vue";

const { Shift_X_Y_Z } = useMagicKeys();

function emitEmptyKeyboardEvent() {
  console.log("x");
  window.dispatchEvent(new KeyboardEvent("keyup"));
}

watch(Shift_X_Y_Z, () => {
  alert("hello world");
});
</script>

<template>
  <div class="flex items-center justify-center w-screen h-screen">
    <button @click="emitEmptyKeyboardEvent">Click me</button>
  </div>
</template>

System Info

System:
    OS: macOS 15.6.1
    CPU: (12) arm64 Apple M4 Pro
    Memory: 80.52 MB / 24.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.19.0 - /Users/davidjohnston/.nvm/versions/node/v22.19.0/bin/node
    npm: 11.6.2 - /Users/davidjohnston/.nvm/versions/node/v22.19.0/bin/npm
    pnpm: 10.16.1 - /Users/davidjohnston/Library/pnpm/pnpm
    bun: 1.2.21 - /Users/davidjohnston/.bun/bin/bun
  Browsers:
    Brave Browser: 141.1.83.120
    Chrome: 142.0.7444.60
    Edge: 142.0.3595.53
    Safari: 18.6
  npmPackages:
    @vueuse/core: ^14.0.0 => 14.0.0 
    vue: ^3.5.22 => 3.5.22

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions