Skip to content
advanced

Review: a listener that outlives its component

This is recall. The code looks finished and is wrong. Find the defect and fix it. You are graded on tests you cannot see.

You asked a model for a composable that runs a callback when a given key is pressed — the standard keyboard-shortcut helper. It produced this, with tests. The tests pass.

import { onMounted } from 'vue'

/**
 * Calls `handler` whenever `key` is pressed, for as long as the owning
 * component is mounted.
 */
export function useKeyPress(key: string, handler: () => void): void {
  onMounted(() => {
    document.addEventListener('keydown', (event) => {
      if (event.key === key) {
        handler()
      }
    })
  })
}
review — find the defectCtrl+↵ submits · Ctrl+Shift+↵ runsstarter code