Sergey
Sergey

Reputation: 1075

Cancel separate and all axios requests

Problem: I have React app that fires axios requests and you can cancel them one by one, clicking on buttons. Now I created one more button that should cancel all requests at once, but I don't know how to do it, because I already have cancelToken config in requests for separate cancelling.

Question: how to cancel all three requests from my code example by clicking on a button?

Code example:

Component Wrapper.jsx:

    const CancelToken = axios.CancelToken;

    <RequestComponent cancelToken={CancelToken}>
    <RequestComponent cancelToken={CancelToken}>
    <RequestComponent cancelToken={CancelToken}>

    <button onClick={/* Something here */}>Cancel all requests</button>

Component RequestComponent.jsx:

    let cancel;

    // new axios request
    axios.get('/user/12345', {
      cancelToken: new this.props.CancelToken(function executor(c) {
        cancel = c;
      })
    });

    // cancel this one particular request
    <button onClick={cancel('Request canceled')}>Cancel this one request</button>

I read axios documentation, but still can't figure this out.

Upvotes: 2

Views: 1338

Answers (1)

eskawl
eskawl

Reputation: 637

In the parent component which hold the RequestComponents, pass an additional prop which will be called after a request.

<RequestComponent cancelToken={CancelToken} onRequest={persistCancel}>
<RequestComponent cancelToken={CancelToken} onRequest={persistCancel}>
<RequestComponent cancelToken={CancelToken} onRequest={persistCancel}>

When a request is made, persist the cancel function.

axios.get('/user/12345', {
  cancelToken: new this.props.CancelToken(function executor(c) {
    cancel = c;
    this.props.onRequest(c);
  })
});

In the parent component, store the cancel function

persistCancel = (cancel) => {
    this.setState({cancels: [...this.state.cancels, cancel]}
}

Call these functions when you want to cancel all of them.

<button onClick={()=>{this.state.cancels.forEach((c) => c())}}>Cancel all requests</button>

Upvotes: 3

Related Questions