Last active
November 8, 2017 01:26
-
-
Save export-mike/7f98692319e7c793dfb536ca73a8a8b6 to your computer and use it in GitHub Desktop.
ReactRequestHigherOrderComponent - with custom Loading component, leverages async await
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
import React from 'react'; | |
import Api from '../Api'; | |
import Loading from '../components/Loading'; | |
import Title from '../components/Title'; | |
const withRequest = ({ fetch, prop, defaultState, LoadingComponent }) => Component => class WithRequest extends React.Component { | |
state = { | |
[prop]: defaultState, | |
loading: false, | |
error: false | |
} | |
retry() { | |
this.componentWillMount(); | |
} | |
async componentWillMount() { | |
try { | |
this.setState({ | |
...this.state, | |
loading: true, | |
error: false | |
}) | |
const result = await fetch(this.props); | |
this.setState({ | |
...this.state, | |
[prop]: result, | |
loading: false | |
}); | |
} catch (e) { | |
this.setState({ | |
...this.state, | |
loading: false, | |
error: true | |
}); | |
console.error(e); | |
} | |
} | |
render() { | |
return <LoadingComponent loading={this.state.loading} error={this.state.error} retry={this.retry}> | |
<Component {...this.props} {...this.state}/> | |
</LoadingComponent>; | |
} | |
} | |
const Notification = ({ notification }) => <div> | |
<Title>{notification.title}</Title> | |
</div> | |
export default withRequest({ | |
fetch: props => Api.notification(props.match.params.id), | |
prop: 'notification', | |
defaultState: {}, | |
LoadingComponent: Loading | |
})(Notification); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment