β οΈ 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:
Top comments (0)