React Cancelable
React Higher-Order Component to handle promise cancelation when the component unmounts.
React Cancelable is a Higher-Order Component that wraps handlers into new functions that return a Cancelable
, which are safely canceled when the component unmounts.
Status
Installation
npm install react-promise-cancelable promise-cancelable --save
yarn add react-promise-cancelable promise-cancelable
API
cancelable()
: HigherOrderComponent
Accepts a function that maps owner props to a new collection of props that are passed to the base component. The remapped props are wrapped functions around a new Cancelable
that are safely canceled when the component unmounts.
Note: Every handlers that are not functions are therefore ignored.
Usage
Basic example
One of the use cases is to avoid calling setState()
after a component has unmounted. The Higher-Order Component keeps a list of registered cancelables and calls the Cancelable.cancel()
method for each registered cancelable.
// ./delay.js; { const id = ; ; };
// ./my-component.js;;; state = value: 'Not called' ; { // When the component unmounts the cancelable returned by `delay` is // canceled, so the `setState` method is not called. thiscancelable = thisprops; } { if thiscancelable // Stop the progress of an ongoing asynchronous task. thiscancelable; } { return <div> <div> thisstatevalue </div> <button onClick=thisupdateValue> 'Click!' </button> <button onClick=thiscancel> 'Cancel!' </button> </div> ; } delay MyComponent;
Canceling a HTTP request
Some HTTP clients provide a way to cancel requests. axios has a cancellation API using a cancel token.
We can create a new instance of axios
and patch its methods in order to make them cancelable.
//./axios.js;; const makeCancelableRequest = { return { const CancelToken = axios; // Create a cancellation token every time the method is called. This way we // avoid creating global tokens that could cancel all the subscribed requests. const source = CancelTokensource; // We create a new instance internally to avoid polluting the global // instance defaults. const instance = axios; instancedefaultscancelToken = sourcetoken; instance method...args ; ; };}; const instance = axios; // Example with `get`.instanceget = ; ;
Now we can import our own axios
instance and use it to create new requests that can be easily canceled whether when the user navigates to another page or by explicitly calling the cancel()
method of that subscription.
// ./app.js; state = loading: false ; { if thiscancelable // Cancel the previous request. thiscancelable; // Show an initial loader. this; // When the component unmounts this request will be canceled. thiscancelable = thisprops; } { return <div> thisstateloading ? <Loader /> : null <button onClick=thisgetUsers>'Get users!'</button> </div> ; } axiosApp;
Related
Licence
MIT © João Granado