Created
May 19, 2019 06:50
-
-
Save chrisza4/1becf5dd9e55b3fddfe5dbf594a062bf to your computer and use it in GitHub Desktop.
ApiConnector
This file contains hidden or 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
| class ApiConnector extends React.Component { | |
| componentDidMount = async () => { | |
| this.setState({ | |
| loadingState: 'loading', | |
| }) | |
| try { | |
| const data = await this.props.loadData() | |
| this.setState({ | |
| loadingState: 'loaded', | |
| data, | |
| }) | |
| } catch (err) { | |
| this.setState({ | |
| loadingState: 'error', | |
| errorMessage: err.message, | |
| }) | |
| } | |
| } | |
| render() { | |
| if (!this.props.renderLoading) { | |
| return <div>Holy shit!! Please provider loading state</div> | |
| } | |
| if (!this.props.renderError) { | |
| return ( | |
| <div> | |
| <h2>Good developer always handle error case.</h2> | |
| <p> | |
| It is naive to assume that Api call via network going to always be | |
| success | |
| </p> | |
| <p>Please provide renderError</p> | |
| </div> | |
| ) | |
| } | |
| switch (this.state.loadingState) { | |
| case 'loading': | |
| return this.props.renderLoading() | |
| case 'error': | |
| return this.props.renderError() | |
| default: | |
| return this.props.render(this.state.data) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment