Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an axios cancel token?

Tags:

axios

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?

like image 378
cocoPuffs Avatar asked Feb 22 '18 16:02

cocoPuffs


People also ask

What does cancel token do?

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.

How do I cancel axios calls?

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.


2 Answers

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.

like image 79
A. Nadjar Avatar answered Sep 19 '22 13:09

A. Nadjar


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()

like image 30
Hunaid Hassan Avatar answered Sep 18 '22 13:09

Hunaid Hassan