@crabas0npm/officiis-sit-facilis
v1.0.0
Published
[![npm](https://img.shields.io/npm/v/@crabas0npm/officiis-sit-facilis.svg)](https://www.npmjs.com/package/@crabas0npm/officiis-sit-facilis) ![downloads](https://img.shields.io/npm/dt/@crabas0npm/officiis-sit-facilis.svg) [![CI](https://github.com/crabas0n
Downloads
4
Maintainers
Keywords
Readme
Make-Cancellable-Promise
Make any Promise cancellable.
tl;dr
- Install by executing
npm install @crabas0npm/officiis-sit-facilis
oryarn add @crabas0npm/officiis-sit-facilis
. - Import by adding
import makeCancellablePromise from '@crabas0npm/officiis-sit-facilis
. - Do stuff with it!
const { promise, cancel } = makeCancellablePromise(myPromise);
User guide
makeCancellablePromise(myPromise)
A function that returns an object with two properties:
promise
and cancel
. promise
is a wrapped around your promise. cancel
is a function which stops .then()
and .catch()
from working on promise
, even if promise passed to makeCancellablePromise
resolves or rejects.
Usage
const { promise, cancel } = makeCancellablePromise(myPromise);
Typically, you'd want to use makeCancellablePromise
in React components. If you call setState
on an unmounted component, React will throw an error.
Here's how you can use makeCancellablePromise
with React:
function MyComponent() {
const [status, setStatus] = useState('initial');
useEffect(() => {
const { promise, cancel } = makeCancellable(fetchData());
promise.then(() => setStatus('success')).catch(() => setStatus('error'));
return () => {
cancel();
};
}, []);
const text = (() => {
switch (status) {
case 'pending':
return 'Fetching…';
case 'success':
return 'Success';
case 'error':
return 'Error!';
default:
return 'Click to fetch';
}
})();
return <p>{text}</p>;
}
License
The MIT License.