[Vuejs]-Custom callback stack for search input

0👍

I wouldn’t await all the request if you don’t need the result anyway. Instead, you could abort running requests with AbortController when starting a new request, which rejects all current awaits. But you would have to build this into your searchRepos().

Something like this should work:

const debounceWithAbort = (callback, wait) => {
  let timeoutId = null;
  let controller = null; // <--- add controller reference
  return (...args) => {
    window.clearTimeout(timeoutId);
    if (controller) { // <--- abort running fetches
      controller.abort()
    }
    timeoutId = window.setTimeout(() => {
      controller = new AbortController // <--- create controller
      callback.apply(null, [controller.signal, ...args]); // <--- pass in signal
    }, wait);
  };
}

then you can pass the signal to searchRepos():

      this.handleChange = debounceWithAbort(async (signal, ev) => { // <--- take signal
        const { target: { value: search } } = ev;
        if (!search) {
          this.repos = [];
          return
        }
        this.loading = true;
        try{
          const response = await searchRepos({ search }, signal); // <--- pass signal to request and use it there
          const repos = await response.json(response);
        } catch (e) {
          return // <--- aborted
        }
        this.repos = repos?.items;
        this.loading = false;
      }, 500);
    }

What you do with signal inside searchRepos() depends on how you send the request, but I think by now AbortController is supported everywhere.

Leave a comment