This page looks best with JavaScript enabled

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

 ·   ·  ☕ 2 min read

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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things