This content originally appeared on DEV Community and was authored by Dzung Nguyen
โ ๏ธ 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();
โ
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.");
Follow me to stay updated with my future posts:
This content originally appeared on DEV Community and was authored by Dzung Nguyen

Dzung Nguyen | Sciencx (2025-02-15T14:37:48+00:00) ๐ Efficient API Calls with Axios: Cancelling Unwanted Requests ๐. Retrieved from https://www.scien.cx/2025/02/15/%f0%9f%9a%80-efficient-api-calls-with-axios-cancelling-unwanted-requests-%f0%9f%9a%80/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.