Is it good to use events like “onkeyup” to make requests?

ahmadfathy

Ahmad Fathy

Posted on April 21, 2020

Is it good to use events like “onkeyup” to make requests?

Why are we using events like "onkeyup"?

Well, It’s better from UX (user experience) side, You just hit the letters and walah here is you result.
But there is an issue here…

First of all let’s see how to make a request with “onkeyup” event?

Let’s fetch some dad jokes…


<input type="search" id="search-box">
<ul id="search-result"></ul>
Enter fullscreen mode Exit fullscreen mode
let searchBox = document.querySelector("#search-box"),
    searchResult = document.querySelector("#search-result");
let config = {
  headers: {
    Accept: "application/json"
  }
};

searchBox.onkeyup = function(e) {
  if(e.target.value.trime().length > 0) {
    let searchText = e.target.value;
    fetch("https://icanhazdadjoke.com/search?term=" + searchText, config)
      .then(res => res.json())
      .then(data => {
        searchResult.innerHTML = '';
        data.results.forEach((joke) => {
          searchResult.innerHTML += "<li>" + joke.joke +"</li>"
        })
      })
  }
} 

Enter fullscreen mode Exit fullscreen mode

cOo0O0ol all things go just fine.
But when you type a letter and type another one no matter how fast you are (except if you are faster than eminem)there are two requests have been sent and you actually just want the last one but the first one maybe is pending in the background and maybe it isn’t completed yet and that is not a good thing for performance.

So what can we do to abort the previous request?

We can use AbortController
A controller is an extremely simple object.
It has a single method abort(), and a single property signal.
When abort() is called:
abort event triggers on controller.signal
controller.signal.aborted property becomes true.

so we will make a little change in the code

we will add this line before the function

let controller = null; 
Enter fullscreen mode Exit fullscreen mode

and we will add this if statement on the function to abort the previous request if the controller is not null

searchBox.onkeyup = function(e) {
  if (controller !== null) {
    controller.abort();
  }
  // the rest of the code
}
Enter fullscreen mode Exit fullscreen mode

Then we will add last two lines of code after if statement

searchBox.onkeyup = function(e) {
  if (controller !== null) {
    controller.abort();
  }
  controller = new AbortController();
  config.signal = controller.signal;
  // the rest of the code
}
Enter fullscreen mode Exit fullscreen mode

now when we type a letter and type another one before the first request done, the first request will be canceled
the first request canceled

💖 💪 🙅 🚩
ahmadfathy
Ahmad Fathy

Posted on April 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related