score:155
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.
Example:
const cancelTokenSource = axios.CancelToken.source();
axios.get('/user/12345', {
cancelToken: cancelTokenSource.token
});
// Cancel request
cancelTokenSource.cancel();
score:0
Starting from v0.22.0 Axios supports AbortController to cancel requests in fetch API way:
const controller = new AbortController();
axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// cancel the request
controller.abort()
CancelToken deprecated You can also cancel a request using a CancelToken.
The axios cancel token API is based on the withdrawn cancelable promises proposal.
This API is deprecated since v0.22.0 and shouldn't be used in new projects
You can create a cancel token using the CancelToken.source factory as shown below:
score:0
import {useState, useEffect} from 'react'
export function useProfileInformation({accessToken}) {
const [profileInfo, setProfileInfo] = useState(null)
useEffect(() => {
const abortController = new AbortController()
window
.fetch('https://api.example.com/v1/me', {
headers: {Authorization: `Bearer ${accessToken}`},
method: 'GET',
mode: 'cors',
signal: abortController.signal,
})
.then(res => res.json())
.then(res => setProfileInfo(res.profileInfo))
return function cancel() {
abortController.abort()
}
}, [accessToken])
return profileInfo
}
// src/app.jsx
import React from 'react'
import {useProfileInformation} from './hooks/useProfileInformation'
export function App({accessToken}) {
try {
const profileInfo = useProfileInformation({accessToken})
if (profileInfo) {
return <h1>Hey, ${profileInfo.name}!</h1>
} else {
return <h1>Loading Profile Information</h1>
}
} catch (err) {
return <h1>Failed to load profile. Error: {err.message}</h1>
}
}
score:4
Using cp-axios wrapper you able to abort your requests with three diffent types of the cancellation API:
1. Promise cancallation API (CPromise):
const cpAxios= require('cp-axios');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
const chain = cpAxios(url)
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
setTimeout(() => {
chain.cancel();
}, 500);
2. Using AbortController signal API:
const cpAxios= require('cp-axios');
const CPromise= require('c-promise2');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
const abortController = new CPromise.AbortController();
const {signal} = abortController;
const chain = cpAxios(url, {signal})
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
setTimeout(() => {
abortController.abort();
}, 500);
3. Using a plain axios cancelToken:
const cpAxios= require('cp-axios');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
const source = cpAxios.CancelToken.source();
cpAxios(url, {cancelToken: source.token})
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
setTimeout(() => {
source.cancel();
}, 500);
4. Usage in a custom React hook (Live Demo):
import React from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpAxios from "cp-axios";
/*
Note: the related network request will be aborted as well
Check out your network console
*/
function TestComponent({ url, timeout }) {
const [cancel, done, result, err] = useAsyncEffect(
function* () {
return (yield cpAxios(url).timeout(timeout)).data;
},
{ states: true, deps: [url] }
);
return (
<div>
{done ? (err ? err.toString() : JSON.stringify(result)) : "loading..."}
<button onClick={cancel} disabled={done}>
Cancel async effect (abort request)
</button>
</div>
);
}
Update
Axios v0.22.0+ supports AbortController
natively:
const controller = new AbortController();
axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// cancel the request
controller.abort()
score:5
This is how I did it using promises in node. Pollings stop after making the first request.
var axios = require('axios');
var CancelToken = axios.CancelToken;
var cancel;
axios.get('www.url.com',
{
cancelToken: new CancelToken(
function executor(c) {
cancel = c;
})
}
).then((response) =>{
cancel();
})
score:6
There is really nice package with few examples of usage called axios-cancel. I've found it very helpful. Here is the link: https://www.npmjs.com/package/axios-cancel
score:6
https://github.com/axios/axios#cancellation
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
let url = 'www.url.com'
axios.get(url, {
progress: false,
cancelToken: source.token
})
.then(resp => {
alert('done')
})
setTimeout(() => {
source.cancel('Operation canceled by the user.');
},'1000')
score:24
Typically you want to cancel the previous ajax request and ignore it's coming response, only when a new ajax request of that instance is started, for this purpose, do the following:
Example: getting some comments from API:
// declare an ajax request's cancelToken (globally)
let ajaxRequest = null;
function getComments() {
// cancel previous ajax if exists
if (ajaxRequest ) {
ajaxRequest.cancel();
}
// creates a new token for upcomming ajax (overwrite the previous one)
ajaxRequest = axios.CancelToken.source();
return axios.get('/api/get-comments', { cancelToken: ajaxRequest.token }).then((response) => {
console.log(response.data)
}).catch(function(err) {
if (axios.isCancel(err)) {
console.log('Previous request canceled, new request is send', err.message);
} else {
// handle error
}
});
}
score:26
import React, { Component } from "react";
import axios from "axios";
const CancelToken = axios.CancelToken;
let cancel;
class Abc extends Component {
componentDidMount() {
this.Api();
}
Api() {
// Cancel previous request
if (cancel !== undefined) {
cancel();
}
axios.post(URL, reqBody, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
})
.then((response) => {
//responce Body
})
.catch((error) => {
if (axios.isCancel(error)) {
console.log("post Request canceled");
}
});
}
render() {
return <h2>cancel Axios Request</h2>;
}
}
export default Abc;
score:41
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
})
Source: stackoverflow.com
Related Query
- how to cancel/abort ajax request in axios
- How to abort pending jquery ajax request when user navigates to other page?
- How do I cancel this axios request
- How to cancel Axios request in react redux with hooks?
- How to cancel api request using redux-observable and axios
- How to abort Axios request in React apps using async/await?
- How To Abort Axios GET Request While State Is Updating?
- How to make AJAX request in redux
- How do I create configuration for axios for default request headers in every http call?
- How to use axios / AJAX with redux-thunk
- How to show progress of Axios during get request (not download or upload)
- Cancel axios get request when typing reactjs
- how to cancel previous axios with redux in react
- How to avoid sending multiple duplicate AJAX requests in axios
- How do I cancel an Image.getSize() request in React Native?
- Cancel async request on unmount with axios
- How to have config parameter in axios post request with headers required
- How to display an image which comes back from an axios request (React)?
- How to use rxjs ajax operator instead of axios in my react project?
- Is there any alternative to CORS google chrome extension? How to make successful ajax request without using CORS?
- how to set api request to google drive api using axios
- Cancel async Axios GET request - React hooks
- React - How to Update State After AJAX Request
- how do I make a post and get request with ReactJS, Axios and Mailchimp?
- How to make AJAX GET request on the client to external site with React
- Cancel request in Axios Instance class
- How to fix random http request (404 response) from Axios
- Correct way to cancel async axios request in a React functional component
- How to cancel previous fetch request in new fetch request in react?
- Cancel only current axios request in React application
More Query from same tag
- Why return multiple elements in React is not allowed?
- How do you manage component dependency order with Facebook React?
- Use Web3 and Metamask in React
- React with chart js, labelling problems in multiple datasets for doughnut chart
- I am waiting for a response from the server, but want to show some timeout message in the UI after 1 minute while waiting for the response
- How to display in input textbox of credit card number the 4 numbers then space?
- Browserify & ReactJS issue
- Configuring onSubscriptionData for React Apollo subscription client
- Is it possible to make API only once per app in React
- How to send properly a message in twilio conversation with react?
- Using React Router to determine ReactApp URL Search
- How to disable the selection of an item when the first letter of the option is pressed in the Select component?
- React-Router-Dom-v4 version of this code?
- AntDesign deselect Radio Group checked button
- Using React, how do you pass a function from a parent component to a child component and run it in the useEffect hook?
- Can't perform a react state update error when using useEffect in a custom express route
- How to plot multiple points of different color in the same layer using mapbox?
- TypeError: Cannot read property 'onMouse' of undefined React Class Component
- React responsive nav component es6 function not firing
- TypeScript Styled-Components Theme property returning undefined
- Creating depth chart using highcharts and creating bids and asks in such a way that bids and asks are created from center of chart
- Partial Redirect in React-Router 4.0.0.alpha6
- React component not re-rendering on state change due to Memoize
- React Bootstrap on mobile: confusing focus styling
- Module not found: Can't resolve 'fs' - NextJS
- How to fix 'HTML5 currentTime always sets to zero'
- Dropdown dont show onClick React.js
- Why is it considered ok to mutate a shallow copy of my state?
- Typescript error "children does not exists on type IntrinsicAttributes & RefAttributes<unknown>'.* " on react component
- React/Redux accessing props