https://github.com/axios/axios#cancellation
I was looking at how to cancel an upload PUT request and came across this section in the documentation. Why do you need a token to cancel? What is the flow or process in simple terms? How is it used?
A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource.
To cancel or abort ajax requests in Axios in a React app, we can use the Axios cancel token feature. 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.
A good nifty example is when you have a search component, and imagine on every keyboard strike into the input tag, an axios request is made, which can lead to an overload of requests.
The cancel token idea can help cancel the previous request, made by previous keyboard hit.
This link makes an enlightening example in reactjs.
An axios request normally returns you a promise. And you can't source back to the original request using that promise. Using the cancellationToken
you associate that specific request to that source that you get form var source = CancelToken.source();
I don't know about the inner workings but my guess is calling cancel()
on that source as mentioned in the docs, instantly calls reject()
on the promise you are subscribed to with the error string passed to cancel()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With