How to check Api is triggered or not and how to abort the api if its triggered

Viewed 401

I am creating a search page, to search for some data on keyup, for each keyup a API being called, but I want to stop the previous call if 2nd API being called.

myFunction(term) {
    const controller = new AbortController();
    const signal = controller.signal;
    controller.abort();
    var apiUrl = window.BASE_URL + '/search?param=' + term;
    console.log(apiUrl);
    this.setState({
      searching: true
    });
    return fetch(apiUrl, { credentials: 'include', signal: signal })
      .then(this.handleErrors)
      .then(response => response.json())
      .then(responseJson => {
         console.log(responseJson);
      })
      .catch(error => {
        console.error(error);
      });
  }
2 Answers

You already providing the signal to the fetch call, but since you initialised it inside your function scope, the outer world has no reference to it, so it can't be used.

So f.ex. pass it as a param to your function:

const controller = new AbortController();
const signal = controller.signal;

myFunction(term, signal) { ... }

Then whenever needed call abort:

signal.abort()

Also be sure you are not using IE as it is not supported on that browser.


Other option to store signal object outside and reinitialise it when myFunction is called:

signal;

myFunction(term) {
  this.signal ? signal.abort() : false;

  const controller = new AbortController();
  this.signal = controller.signal;

  < ... >
}

An example to cancel previous fetch requests:

const controller = useRef<AbortController>() // useRef: for function component. 
// You can create a property in a class component to store this 
// (e.g. `this.controller = null` in your constructor)  

function fetchAndAbortPrevious() {
  controller.current?.abort()
  controller.current = new AbortController()
  fetch('https://cat-fact.herokuapp.com/facts', {
    signal: controller.current.signal,
  })
    .then((response) => response.json())
    .then((response) => console.log(response))
    .catch((err) => console.log('error: ', err))
}
Related