Search code examples
javascriptreactjsfunctionapiecmascript-2016

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


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);
      });
  }

Solution

  • 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))
    }