Skip to content

Instantly share code, notes, and snippets.

@rowlandekemezie
Last active March 23, 2019 12:22
Show Gist options
  • Save rowlandekemezie/8632e81ae2960df8d02947b8b743b268 to your computer and use it in GitHub Desktop.
Save rowlandekemezie/8632e81ae2960df8d02947b8b743b268 to your computer and use it in GitHub Desktop.
A basic implementation of Ajax within the react component.
// UserProfile Component
class UserProfile extends React.Component {
constructor() {
super();
this.state = {
user: []
}
}
// componentDidMount lifecycle method allows dynamic behaviour, AJAX,
// side effects, etc. We issue our API call here and set the
// response to component's state.
componentDidMount() {
gitHubApi('rowlandekemezie').then(data => {
this.setState({
user: data
});
})
}
// Here, we destructure component's state and render the user details.
render() {
const { user } = this.state;
return <div>
<h1> User details </h1>
<img src={user.avatar_url} />
<p><a href={user.html_url}>{user.login}</a></p>
</div>
}
}
// Function that calls our specified endpoint on Github
// We're using **fetch** method from **fetch API** to make the call.
const gitHubApi = (username) => {
return fetch(`https://api.github.com/users/${username}`)
.then(response => {
return response.json();
})
.then(({ login, avatar_url, html_url }) => ({ login, avatar_url, html_url }))
.catch(error => {
throw error;
})
};
// We mount the UserProfile component to the DOM
ReactDOM.render(<UserProfile />, document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment