cancelbl
v1.0.1
Published
Yet another make-cancelable Promise wrapper
Downloads
2
Maintainers
Readme
cancelbl
Yet another cancelable Promise wrapper, inspired by this article from React blog.
Installation
# npm
npm install cancelbl
# yarn
yarn add cancelbl
Or you can copy-paste it from here if ES6 sounds good to you.
Overview
For React components, that use fetch to update the state, unmounting can lead to the following issue:
setState(…): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op
The correct way to fix this issue, according to the article, is to cancel any callbacks in componentWillUnmount
, prior to unmounting.
Suggested makeCancelable
wraps target promise and returns cancel()
function, which can be called in componentWillUnmount
.
The advantage of this implementation is that it wraps and handles the promise in a single statement. Check out Example section below to see how simple it is.
For complete specification, see cancelbl.test.js.
Usage: React component
A typical example of two subsequent fetches without taking care of the method setState
:
constructor()
{
super();
this.state = {
item: {},
relatedItems: {}
};
}
componentDidMount() {
fetchResource(this.props.url)
.then(item => {
this.setState({item})
fetchRelatedResources(item)
.then(relatedItems => {
this.setState({item});
})
.catch(error => { /* handle */ })
})
.catch(error => { /* handle */ });
}
Let's import cancelbl:
import cancelbl from 'cancelbl';
And update the component:
constructor()
{
super();
this.state = {
item: {},
relatedItems: {}
};
// set initial cancel object:
this.cancel = cancelbl.default;
}
componentDidMount() {
// wrap promises with .make and .with:
this.cancel = cancelbl.make(
fetchResource(this.props.url),
item => {
this.setState({item});
this.cancel.with(
fetchRelatedResources(item),
relatedItems => this.setState({relatedItems}),
error => { /* handle */ }
);
},
error => { /* handle */ }
);
}
componentWillUnmount() {
// the magic happens here:
this.cancel.do();
}
Here we go.
Running the tests
# with npm
npm test
# with yarn
yarn test
Other implementations
Please check out react-unplug
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Versioning
SemVer is used for versioning. For the versions available, see the tags on this repository.
License
This project is licensed under the MIT License - see the LICENSE file for details.