Wait for User to Stop Typing in Search Fields on Vue UI

Let us see how we can easily accumulate requests when user types in a search (or auto-complete) fields and collate them in one go.

When implementing the ‘instant search’ fields in Vue, the cycle of events is pretty standard -

  1. User keys in characters
  2. System keeps getting those characters and sending them to the server for processing
  3. System reacts to changes from server and displays search results

The same cycle repeats for fields include auto-complete that take user action and return stuff from server.

We implement such a behaviour like so -

<template>
  <input v-model="search" label="Search" />
</template>

<script>
  export default {
    data() {
      return {
        search: ""
      };
    },

    watch: {
      search: function(val) {
        this.fetchResults({ query: this.search });
        // handle server request locally or in Vuex
        // not provided here to keep this illustration more focussed
      }
    }
  };
</script>

Although the multiple requests sent on each key stroke works, they cause too many requests to server without tangible positive results. Not really a problem if you have a good server, but that is not the case with me.

So, I always tend to delay the server request until a certain time and send the request after that time. This behaviour is also called debounce and a few libraries have automatic management of such behaviour.

  • Any key strokes during that time are therefore sent at once.
  • We do not send multiple requests for any number of key strokes during the wait.

Following is the code to implement such a behaviour -

<template>
  <input v-model="search" label="Search" />
</template>

<script>
  export default {
    data() {
      return {
        search: "",
        awaitingSearch: false
      };
    },

    watch: {
      search: function(val) {
        if (!this.awaitingSearch) {
          setTimeout(() => {
            this.fetchResults({ query: this.search });
            this.awaitingSearch = false;
          }, 1000); // 1 sec delay
        }
        this.awaitingSearch = true;
      }
    }
  };
</script>

watch for search will wait for 1 second before sending out the changed search string to server. You can change it to anywhere between 0.3s to 1s for an acceptable user experience.

comments powered by Disqus