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?

+3


source to share


2 answers


The easiest way I've found is to save source

in state and use source.cancel

if request is sent.



componentWillUnmount() { if(isLoading) { source.cancel() } }

0


source


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

0


source







All Articles