-
-
Save gemanepa/8fd486ba4994a4e463e63de1fd1d7984 to your computer and use it in GitHub Desktop.
React example - fetch data from web API
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
| import React from 'react'; | |
| class UserProfiles extends React.Component { | |
| constructor(){ | |
| super(); | |
| this.state = { | |
| name: {title: '', first: '', last: ''}, | |
| image: '' | |
| }; | |
| // fix the this value | |
| this.getUser = this.getUser.bind(this); | |
| } | |
| componentWillMount() { | |
| this.getUser(); | |
| } | |
| getUser() { | |
| fetch('https://randomuser.me/api/') | |
| .then(response => { | |
| if(response.ok) return response.json(); | |
| throw new Error('Request failed.'); | |
| }) | |
| .then(data => { | |
| this.setState({name: data.results[0].name, | |
| image: data.results[0].picture.medium}); | |
| }) | |
| .catch(error => { | |
| console.log(error); | |
| }); | |
| } | |
| render() { | |
| return ( | |
| <div> | |
| <h1>{`${this.state.name.title} ${this.state.name.first} ${this.state.name.last}`}</h1> | |
| <img alt='Profile' src={this.state.image}></img><br/> | |
| <button onClick={this.getUser}>Get new user.</button> | |
| </div> | |
| ); | |
| } | |
| } | |
| export default UserProfiles; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment