Skip to content

Instantly share code, notes, and snippets.

@jonathanharrell
Last active July 7, 2018 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanharrell/07305dbea0b673870da6eee4d74a0b49 to your computer and use it in GitHub Desktop.
Save jonathanharrell/07305dbea0b673870da6eee4d74a0b49 to your computer and use it in GitHub Desktop.
FetchData React Component Using Render Props
class FetchData extends React.Component {
constructor(props) {
super(props)
this.state = {
loading: false,
results: [],
error: false
}
}
componentDidMount() {
this.fetchData(this.props.url)
}
fetchData(url) {
this.setState({ loading: true })
fetch(url)
.then(data => data.json())
.then(json => {
this.setState({ loading: false, results: json })
})
.catch(error => {
this.setState({ loading: false, error: true })
})
}
render() {
return this.props.render({
loading: this.state.loading,
results: this.state.results,
error: this.state.error
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment