Skip to content

Instantly share code, notes, and snippets.

@jaycosaur
Last active February 24, 2018 05:15
Show Gist options
  • Save jaycosaur/acb42d06ee90d2a1b1d410b33eaf1bf4 to your computer and use it in GitHub Desktop.
Save jaycosaur/acb42d06ee90d2a1b1d410b33eaf1bf4 to your computer and use it in GitHub Desktop.
React Fetch Higher Order Component Example
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} />
}
}
}
@kumilange
Copy link

Since you are using async/await, you don't need to handle promises .then() anymore. I think the code below should work, too :)

try {
  const data = await(await fetch(fetchPath, header)).json()
  this.setState({data: data, isFetching: false})
} catch(err){
  this.setState({isError: err, isFetching: false})
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment