According to the docs, ComponentWillUnmount is able to cancel requests.
I have a page that makes requests for an iframe to load, as well as other requests for page. If the user decides to navigate away from the page while the page is still processing the requests, how can I cancel those requests so that it doesn't affect the other pages the user goes to thereafter?
I should note that I am using Redux and Redux-saga.
Just think of componentWillUnmount
as an opportunity function. It is your opportunity to do as the docs say, perform any additional clean up that React won't do on its own.
As far as XHR requests go, you would need to have a Promise library that supports cancelling the promise. If the library you use does support that then in the componentWillUnmount
you would just make sure you have access to all Promises and cancel each one.
As far as canceling anything else, you just need to use whatever functions are provided for you to cancel whatever it is you want to cancel. If their is a function to cancel it then use the nature of componentWillUnmount
to do so if you need it to be cancelled if the component is being unmounted.
As an example of how we use it where I'm at: If a component is going to make requests, we set a property on the component that is an array and holds all the requests. we would call this this.statePromises
. Whenever we make a request/Promise we would push that Promise into the this.statePromises
. In the componentWillUnmount
we have the following
componentWillUnmount() {
this.statePromises.forEach(p => p.cancel());
}
p being a promise. This only works because of the library, bluebird, that we use for our promises. But that should give you an idea of how you could use componentWillUnmount
to do any additional clean up.
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