Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel async request on unmount with axios

Tags:

reactjs

axios

I have multiple component with axios plugin for some get requests. i need some help to cancel all xhr request with axios on component unmount event in react js. but the axios cancel code is not working. its return me cancel() is not a function error.

Code example:-

import axios from 'axios';


var CancelToken = axios.CancelToken;
var cancel;

axios.get('abc/xyz', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

Please help me to implement cancel request in axios.

Thanks.

like image 258
Sachiv Mehta Avatar asked Sep 08 '17 06:09

Sachiv Mehta


People also ask

How to auto cancel the Axios request when component unmounts?

Auto cancel the request when component unmounts. Let’s fix the problem by changing our code to auto cancel the Axios request when our component unmounts. Inside the useEffect function we now first grab a CancelToken Source from Axios and store it in a constant named source. We can use this to get a CancelToken and actually cancel the request.

How to cancel an Axios request in Salesforce?

To start the process of cancelling an axios request, the following steps are involved: Inside the axios request config, pass the token of the created source variable as the value of the cancelToken key/property.

How to delete a subscription in Axios?

The cleanup function can be used to dispose off the subscription. Once the request is cancelled, it is also required to check whether the reason for the failed request is the Abort or did it actually fail. When using AbortControlled, if a request is aborted, the error.name property will be “ AbortError ” In Axios we need to generate a Cancel Token.

How do I cancel a request using the Axios cancel token?

You can cancel a request using a cancel token. The axios cancel token API is based on the withdrawn cancelable promises proposal. You can create a cancel token using the CancelToken.source factory as shown below: const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).


1 Answers

It is quite simple. Create the request in componentDidMount and cancel it in componentWillUnmount. Replace the url with an existing JSON file and this snippet will work as expected:

class MyComponent extends Component {
  constructor (props) {
    super(props)

    this.state = {
      data: []
    }
  }

  componentDidMount () {
    this.axiosCancelSource = axios.CancelToken.source()

    axios
      .get('data.json', { cancelToken: this.axiosCancelSource.token })
      .then(response => {
        this.setState({
          data: response.data.posts
        })
      })
      .catch(err => console.log(err))
  }

  componentWillUnmount () {
    this.axiosCancelSource.cancel('Axios request canceled.')
  }

  render () {
    const { data } = this.state

    return (
     <div>
          {data.items.map((item, i) => {
            return <div>{item.name}</div>
          })}
      </div>
    )
  }
}
like image 188
taseenb Avatar answered Sep 25 '22 01:09

taseenb