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 -
- User keys in characters
- System keeps getting those characters and sending them to the server for processing
- 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 -
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 -
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.