Skip to content

Instantly share code, notes, and snippets.

@bookercodes
Created May 31, 2017 14:23
Show Gist options
  • Save bookercodes/9c7b0d86369db8db763e3a21125c24db to your computer and use it in GitHub Desktop.
Save bookercodes/9c7b0d86369db8db763e3a21125c24db to your computer and use it in GitHub Desktop.
import fetch from "isomorphic-unfetch";
const Talk = ({ title, views }) => (
<div>
<h1>{title}</h1>
<h2>Views: {views}</h2>
</div>
);
class Index extends React.Component {
constructor(props) {
super(props);
this.state = {
talks: props.talks,
hasMore: props.hasMore,
page: 1
};
}
static async getInitialProps() {
const res = await fetch("http://127.0.0.1:3000/api/talks");
const { talks, hasMore } = await res.json();
return {
talks,
hasMore
};
}
async loadMoreTalks() {
const res = await fetch(
`http://127.0.0.1:3000/api/talks?page=${this.state.page + 1}`
);
const { talks, hasMore } = await res.json();
this.setState({
talks: this.state.talks.concat(talks),
page: this.state.page + 1,
hasMore
});
}
loadMore() {
if (this.state.hasMore) {
return <button onClick={e => this.loadMoreTalks()}>Load more</button>;
}
}
render() {
return (
<div>
<h1>Sessions</h1>
{this.state.talks.map(talk => (
<Talk key={talk.id} title={talk.title} views={talk.views} />
))}
{this.loadMore()}
</div>
);
}
}
export default Index;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment