Skip to content

Instantly share code, notes, and snippets.

@martincik
Last active March 15, 2016 08:41
Show Gist options
  • Save martincik/de198d8b346c691f0475 to your computer and use it in GitHub Desktop.
Save martincik/de198d8b346c691f0475 to your computer and use it in GitHub Desktop.
Cancelable component snippet
import cancelable from 'cancelable';
class Contacts extends React.Component {
_cancelables: Array<Object>; // Declare _cancelables for flow
constructor(props) {
super(props);
this._cancelables = []; // Init _cancelables
}
// Whenever the component is unmouted cancel all cancelable callbacks
componentWillUnmount() {
this._cancelables.map(c => c.cancel());
this._cancelables = [];
}
fetchContacts() {
const { dispatch, navigator } = this.props;
// Register all callback you want to be canceled when component is unmouted
let successCallback = cancelable((contacts) => {
this.setState({
contacts: contacts
});
});
this._cancelables.push(successCallback);
// Call async fetch to API (may take longer than the lifecycle of the component)
dispatch(loadContacts(successCallback));
}
Contacts.propTypes = {
dispatch: React.PropTypes.func.isRequired
};
function select() {
return {};
}
export default connect(select)(Contacts);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment