DEV Community

Cover image for πŸš€ Efficient API Calls with Axios: Cancelling Unwanted Requests πŸš€
Dzung Nguyen
Dzung Nguyen

Posted on

πŸš€ Efficient API Calls with Axios: Cancelling Unwanted Requests πŸš€

⚠️ When working with frontend applications, API requests can pile up, especially with features like live search or auto-suggestions.
⚠️ If you don’t cancel outdated requests, you waste bandwidth and slow down your app.
⚠️ Outdated requests can sometimes cause flickering UI

❀️ If you are using Axios to make API requests, here are the two ways you can do:
βœ… Use AbortController (For versions > 0.22)
πŸ‘‰ AbortController provides a signal that Axios listens to.
πŸ‘‰ When abort() is called, it immediately stops the request, preventing unnecessary responses from being processed.

import axios from "axios";

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

axios.get("https://api.example.com/data", { signal })
  .then(response => console.log(response.data))
  .catch(error => {
    if (error.name === "AbortError") {
      console.log("Request was canceled");
    } else {
      console.error("Request failed", error);
    }
  });

// Cancel the request
controller.abort();

Enter fullscreen mode Exit fullscreen mode

βœ… Use CancelToken (For versions < 0.22)
πŸ‘‰ CancelToken creates a cancelable request by passing a token.
πŸ‘‰ The token acts as a reference to the request, allowing Axios to identify and cancel it when needed.
πŸ‘‰ When cancel() is called on the token, Axios recognizes the signal and aborts the associated request, preventing unnecessary processing.

import axios from "axios";

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get("https://api.example.com/data", { cancelToken: source.token })
  .then(response => console.log(response.data))
  .catch(error => {
    if (axios.isCancel(error)) {
      console.log("Request was canceled:", error.message);
    } else {
      console.error("Request failed", error);
    }
  });

// Cancel the request
source.cancel("Operation canceled by the user.");
Enter fullscreen mode Exit fullscreen mode

Follow me to stay updated with my future posts:

Top comments (0)