Last active
March 15, 2016 08:41
-
-
Save martincik/de198d8b346c691f0475 to your computer and use it in GitHub Desktop.
Cancelable component snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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