Last active
February 24, 2018 05:15
-
-
Save jaycosaur/acb42d06ee90d2a1b1d410b33eaf1bf4 to your computer and use it in GitHub Desktop.
React Fetch Higher Order Component Example
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
const fetchHOC = (WrappedComponent, fetchPath, optionalHeader) => { | |
return class extends Component { | |
constructor(props){ | |
super(props) | |
this.state = { | |
data: null, | |
isError: false, | |
isFetching: true | |
} | |
} | |
async componentWillMount(){ | |
const header = optionalHeader?optionalHeader:null | |
await fetch(fetchPath, header) | |
.then(response => response.json()) | |
.then(data => this.setState({data: data})) | |
.catch((err) => this.setState({isError: err})) | |
} | |
render() { | |
return <WrappedComponent | |
data={this.state.data} | |
isError={this.state.isError} | |
isFetching={this.state.isFetching} | |
{...this.props} /> | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since you are using async/await, you don't need to handle promises .then() anymore. I think the code below should work, too :)