Last active
July 7, 2018 20:33
-
-
Save jonathanharrell/07305dbea0b673870da6eee4d74a0b49 to your computer and use it in GitHub Desktop.
FetchData React Component Using Render Props
This file contains 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
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