Skip to content

Instantly share code, notes, and snippets.

@aaronshaf
Last active May 15, 2017 00:49
Show Gist options
  • Save aaronshaf/30bdac233167813236c03491455d809b to your computer and use it in GitHub Desktop.
Save aaronshaf/30bdac233167813236c03491455d809b to your computer and use it in GitHub Desktop.
class ThingsFetcher extends React.Component {
constructor (props) {
super(props)
this.state = {
data: null,
isLoading: false,
wasLoadedSuccessfully: false,
error: null
}
}
componentDidMount () {
this.getThings()
}
componentWillUnmount () {
if (this.cancelAsync) {
this.cancelAsync()
}
}
getThings = () => {
this.cancelAsync = doSomethingAsync()
.then(this.handleSuccess)
.catch(this.handleError)
}
handleSuccess = (data) => {
this.setState({
data,
isLoading: false,
wasLoadedSuccessfully: true,
error: null
})
}
handleError = (error) => {
this.setState({
data: null,
isLoading: false,
wasLoadedSuccessfully: false,
error: error
})
}
render () {
return this.props.children(this.state)
}
})
<div>
<ThingsFetcher>
{(things) => <Things data={things.data} />}
</ThingsFetcher>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment