Skip to content

Instantly share code, notes, and snippets.

@rvcas
Created April 13, 2018 22:44
Show Gist options
  • Save rvcas/2eca23694bb6fcfec042650494a7e5ee to your computer and use it in GitHub Desktop.
Save rvcas/2eca23694bb6fcfec042650494a7e5ee to your computer and use it in GitHub Desktop.
const apiUrl = 'http://localhost:5000/api';
class Overview extends Component {
constructor(props) {
super(props);
// it's nice to do it here because then
// you can init some state with passed props if needed
this.state = {
users: {},
totalPages: 1,
limit: 10,
page: 1,
sortBy: 'customer_id',
ascending: true
};
// very common and will prevent an error
// that could leave you scratching your head.
// you could just use an arrow function in the class body
// but then you end up with inconsistent style
this.getUser = this.getUser.bind(this);
this.changePage = this.changePage.bind(this);
this.changeSort = this.changeSort.bind(this);
}
// notice life cycle methods right after the contructor
// this is just personal style preference
componentDidMount() {
this.getUsers();
}
componentDidUpdate(prevProps, prevState) {
if (prevState.page !== this.state.page) {
this.getUser();
}
}
getUsers() {
axios
.get(
`${this.apiUrl}/users?page=${this.state.page}&limit=${
this.state.limit
}&sortBy=${this.state.sortBy}&ascending=${this.state.ascending}`
)
.then(users => {
this.setState({ users: users.data.docs });
this.setState({ totalPages: users.data.pages });
});
}
changePage(page) {
if (typeof page === 'boolean') {
if (page) {
this.setState(
(prevState, props) => ({
page: prevState.page + 1
}));
} else {
this.setState(
(prevState, props) => ({
page: prevState.page - 1
}));
}
} else {
this.setState({ page: page });
}
}
changeSort(event) {
const heading = event.target.innerHtml;
this.setState({ sortBy: heading });
}
render() {
return (
<div className="overview-list">
<h3>overview</h3>
<Table responsive striped>
<thead>
<tr>
<th onClick={this.changeSort}>customer_id</th>
<th>name</th>
<th>email</th>
<th>birthday</th>
<th>status</th>
</tr>
</thead>
<tbody>
{Object.keys(this.state.users).map(key => (
<UserItem key={key} details={this.state.users[key]} />
))}
</tbody>
</Table>
<Paging
totalPages={this.state.totalPages}
changePage={this.changePage}
/>
</div>
);
}
}
export default Overview;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment