Skip to content

Instantly share code, notes, and snippets.

@Ahed91
Created March 24, 2016 08:50
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 Ahed91/b2c4b9f20ffa4245fb19 to your computer and use it in GitHub Desktop.
Save Ahed91/b2c4b9f20ffa4245fb19 to your computer and use it in GitHub Desktop.
Exercise for "Hacking with React" ch 20 "Refactoring our State Code: Passing Parameters in onClick"
import React from 'react';
import ajax from 'superagent';
class Detail extends React.Component {
constructor(props) {
super(props);
this.state = {
mode: 'commits',
commits: [],
forks: [],
pulls: []
};
}
componentWillMount() {
this.fetchFeed('commits');
this.fetchFeed('forks');
this.fetchFeed('pulls');
}
fetchFeed(type) {
ajax.get(`https://api.github.com/repos/facebook/react/${type}`)
.end((error, response) => {
if(!error && response) {
this.setState({ [type]: response.body });
} else {
console.log(`There was an error fetching ${type} from GitHub`, error);
}
});
}
selectMode(mode) {
this.setState({ mode });
}
render() {
let content;
content = this.state[this.state.mode].map((item, index) => {
let html_url = item.html_url;
let body;
let created_at = '';
let user;
if(this.state.mode === 'commits') {
user = item.author ? item.author.login : 'anonymous';
body = item.commit.message;
} else if(this.state.mode === 'forks') {
user = item.owner ? item.owner.login : 'anonymous';
body = html_url;
created_at = ` at ${item.created_at}`;
} else {
user = item.user ? item.user.login : 'anonymous';
body = item.body;
}
return (<p key={index}>
<strong>{user}</strong>;
<a href={html_url}>{body}</a>{created_at}
</p>);
});
return (<div>
<button onClick={this.selectMode.bind(this, 'commits')}>Show Commits</button>
<button onClick={this.selectMode.bind(this, 'forks')}>Show Forks</button>
<button onClick={this.selectMode.bind(this, 'pulls')}>Show Pulls</button>
{content}
</div>);
}
}
export default Detail;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment