32

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?

cocoPuffs
  • 639
  • 2
  • 6
  • 18

2 Answers2

11

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.

Ahmed Mohamedeen
  • 328
  • 3
  • 11
A. Nadjar
  • 2,440
  • 2
  • 19
  • 20
  • 9
    You would probably want to use debounce for search query instead of canceling previous request each time query change... – Mohammadalijf Jun 07 '20 at 04:09
  • 3
    You would use both debounce and cancelation. There are no guarantees that async requests complete in order, so if you don't cancel an outstanding request you could end up with incomplete results. – noah Feb 25 '21 at 19:55
  • 1
    Link is now at https://www.digitalocean.com/community/tutorials/react-live-search-with-axios – josephdpurcell Aug 26 '22 at 22:43
10

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

Hunaid Hassan
  • 732
  • 5
  • 13