darrenjennings / vue-autosuggest

🔍 Vue autosuggest component.
https://darrenjennings.github.io/vue-autosuggest
MIT License
621 stars 91 forks source link

Arrow key down on un-clicked, empty input causes unrecoverable error #229

Open aaronahearne opened 2 years ago

aaronahearne commented 2 years ago

Relevant code or config

Standard implementation.

What you did:

Navigate to the autosuggest input using keyboard (Tab). Do not click the input. Press the arrow down key.

What happened:

Receive the error: TypeError: Cannot read property '0' of undefined.

Problem description:

computed_section_default0 is not being populated unless the input receives a character or is clicked.

Suggested solution:

As a workaround to this issue, I provided an override to the handleKeyStroke method in the mounted hook of my component:

patchAutoSuggestKeystrokeBug() {
      const autoSuggest = this.$refs.autosuggest;
      const originalHandleKeyStrokeFunc = autoSuggest.handleKeyStroke;

      this.$refs.autosuggest.handleKeyStroke = function (e) {
        // Simulate a click on ArrowDown to open the list of suggestions
        if (e.keyCode === 40 && autoSuggest.$data.currentIndex === null) {
          autoSuggest.listeners.click();
          autoSuggest.$data.currentIndex = 0;
          return;
        }

        originalHandleKeyStrokeFunc(e);
      };
},

This allows the list of suggestions to open when the arrow key down is pressed in this scenario, rather than erroring.