Sometimes, we want to cancel or abort ajax requests in Axios in a React app.
In this article, we’ll look at how to cancel or abort ajax requests in Axios in a React app.
Cancel or Abort Ajax Requests in Axios in a React App
To cancel or abort ajax requests in Axios in a React app, we can use the Axios cancel token feature.
For instance, we can write:
import React, { useRef, useState } from "react";
import axios from "axios";
export default function App() {
const [answer, setAnswer] = useState({});
const cancelTokenSource = useRef();
const request = async () => {
try {
setAnswer({});
cancelTokenSource.current = axios.CancelToken.source();
const { data } = await axios.get("https://yesno.wtf/api", {
cancelToken: cancelTokenSource.current.token
});
setAnswer(data);
} catch (error) {
console.log(error);
}
};
const cancel = () => {
cancelTokenSource.current.cancel();
};
return (
<div>
<button onClick={request}>request</button>
<button onClick={cancel}>cancel</button>
<div>{JSON.stringify(answer)}</div>
</div>
);
}
We define the answer state to store the request response.
And we have the cancelTokenSource ref to store the cancellation token.
In the request function, we set the cancelTokenSource.current to the axios.CancelToken.source() which returns the cancel token object.
And then when we make the request with axios.get , we set cancelToken to the cancel token.
Next, we get the data and set it to answer .
Then we define the cancel function that calls the cancel method that comes with the cancel token to cancel the request.
Conclusion
To cancel or abort ajax requests in Axios in a React app, we can use the Axios cancel token feature.
One reply on “How to Cancel or Abort Ajax Requests in Axios in a React App?”
great post