Canceling route change requests (React / Redux / Axios)
Is there a convenient way to cancel all requests to send in any rerouting via axios
, redux-thunk
, redux
? I know I axios
have a cancellation token that needs to be added to every request and I can call source.cancel(/* message */)
to cancel it.
PS I am currently processing this in componentWillUnmount
. Maybe something better?
source to share
A very simple solution would be to declare a variable isMounted
and set it to false
when the component is unmounted.
Another way to solve this problem is (I'm not sure about axios
but) XMLHttpRequest
has a method abort
. You can call xhr.abort()
for componentWillUnmount
. Check it out here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort
And finally, there is an industry solution :) from the Netflix UI engineers. They have written RxJS middleware and use RxJS operators to start and cancel requests.
The library is called redux-observable
. I recommend taking a look at examples: https://redux-observable.js.org/docs/recipes/Cancellation.html
You can watch a conversation about it here: https://youtu.be/AslncyG8whg
source to share