According to the docs axios supports the AbortController of the fetch API.
Cancellation
Axios supports AbortController to abort requests in fetch API way:
const controller = new AbortController(); axios.get('/foo/bar', { signal: controller.signal }).then(function(response) { //... }); // cancel the request controller.abort()
It's not clear exactly where testController is declared:
let testController: AbortController;
but I suspect it's in the body of the function component and redeclared on a subsequent render cycle.
I suggest using a React ref to store an AbortController, and reference this ref value around your app. This is so the component holds on to a stable reference of the controller from render cycle to render cycle, to be referenced in any useEffect hook cleanup function to cancel in-flight requests if/when the component unmounts.
const abortControllerRef = useRef<AbortController>(new AbortController());
function loadTest() {
TestAPI.getTest(abortControllerRef.current.signal)
.then((e) => {
console.log(e.data);
})
.catch((e) => {
console.error(e);
});
}
useEffect(() => {
const controller = abortControllerRef.current;
return () => {
controller.abort();
};
}, []);
Answer from Drew Reese on Stack OverflowAccording to the docs axios supports the AbortController of the fetch API.
Cancellation
Axios supports AbortController to abort requests in fetch API way:
const controller = new AbortController(); axios.get('/foo/bar', { signal: controller.signal }).then(function(response) { //... }); // cancel the request controller.abort()
It's not clear exactly where testController is declared:
let testController: AbortController;
but I suspect it's in the body of the function component and redeclared on a subsequent render cycle.
I suggest using a React ref to store an AbortController, and reference this ref value around your app. This is so the component holds on to a stable reference of the controller from render cycle to render cycle, to be referenced in any useEffect hook cleanup function to cancel in-flight requests if/when the component unmounts.
const abortControllerRef = useRef<AbortController>(new AbortController());
function loadTest() {
TestAPI.getTest(abortControllerRef.current.signal)
.then((e) => {
console.log(e.data);
})
.catch((e) => {
console.error(e);
});
}
useEffect(() => {
const controller = abortControllerRef.current;
return () => {
controller.abort();
};
}, []);
I would recommend to read this post.
In a nutshell you would like to use useEffect to create controller, and, what is more important, to use return statement to abort the controller.
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
getData(signal)
//cleanup function
return () => {controller.abort();};
}, [fetchClick]);
getData function can then be your axios call in the form:
const getData = async (signal) =>{
const res = await axios.get(url, {signal: signal}).then(...)
}
reactjs - how to cancel/abort ajax request in axios - Stack Overflow
AbortController Signal not cancelling requests with CORS
Trying to understand how timeout works for https.request
Hey there,
If what you mean by "timeout for this request" is that if the response is not received within 1 second, the request should be aborted. Then you need to use the AbortController.
What you do is to create a new abort controller
const controller = new AbortController();
The controller has a signal property you need to provide to the request (axios/fetch). It also has an abort function which will abort the request.
So first create a timeout in 1 sec. which will call the abort function
const timeoutId = setTimeout(() => {
controller.abort();
}, 1000);Now in one second the controller will call the abort function. But, no one is listening yet. So let's add it to the request. I don't use axios but I would assume it is just an option just like when using the built in fetch function.
So now you should provide the signal to the request:
axios.get(url, { signal: controller.signal);If the request goes well, clear the timeout.
clearTimeout(timeoutId);
Everything together looks like this:
// create abort the controller
const controller = new AbortController();
// abort request in 1 sec.
setTimeout(() => {
controller.abort();
}, 1000);
try {
const response = await axios.get(url, { signal: controller.signal);
clearTimeout(timeoutId);
// prints true if response status is 200 or 301. False otherwise
console.log(String(response.ok));
} catch(err) {
// handle network error
}Using await requires the function you write to be async, but you'll understand this soon enough.
I hope this helps. But feel free to ask further questions.
Welcome to nodejs 👍
More on reddit.comAbortController usage
Videos
Axios does not support canceling requests at the moment. Please see this issue for details.
UPDATE: Cancellation support was added in axios v0.15.
EDIT: The axios cancel token API is based on the withdrawn cancelable promises proposal.
UPDATE 2022: Starting from v0.22.0 Axios supports AbortController to cancel requests in fetch API way:
Example:
const controller = new AbortController();
axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// cancel the request
controller.abort()
Using useEffect hook:
useEffect(() => {
const ourRequest = Axios.CancelToken.source() // <-- 1st step
const fetchPost = async () => {
try {
const response = await Axios.get(`endpointURL`, {
cancelToken: ourRequest.token, // <-- 2nd step
})
console.log(response.data)
setPost(response.data)
setIsLoading(false)
} catch (err) {
console.log('There was a problem or request was cancelled.')
}
}
fetchPost()
return () => {
ourRequest.cancel() // <-- 3rd step
}
}, [])
Note: For POST request, pass cancelToken as 3rd argument
Axios.post(`endpointURL`, {data}, {
cancelToken: ourRequest.token, // 2nd step
})