Skip to content

Instantly share code, notes, and snippets.

@johnnykoo84
Created April 17, 2019 14:59
Show Gist options
  • Save johnnykoo84/b3f34ce317677606bcf4c7f14314abac to your computer and use it in GitHub Desktop.
Save johnnykoo84/b3f34ce317677606bcf4c7f14314abac to your computer and use it in GitHub Desktop.
loadMoreArticles = direction => {
const { allArticles, currentCategory } = this.state;
const currentCategoryId = this.categories.find(
category => category.name === currentCategory
).id;
const currentCategoryArticles = allArticles.filter(
article => article.UserId === currentCategoryId
);
const pagedArticles = page => {
const lastIndex = page * this.articlesPerPage;
const firstIndex = lastIndex - this.articlesPerPage;
return currentCategoryArticles.slice(firstIndex, lastIndex);
};
const getLastPage = () =>
Math.floor(currentCategoryArticles.length / this.articlesPerPage);
// eslint-disable-next-line default-case
switch (direction) {
case 'prev':
this.setState(prevState => {
if (prevState.currentPage === 1) {
return {
currentPage: getLastPage(),
currentArticles: pagedArticles(getLastPage())
};
} else {
return {
currentPage: prevState.currentPage - 1,
currentArticles: pagedArticles(prevState.currentPage - 1)
};
}
});
break;
case 'next':
this.setState(prevState => {
if (prevState.currentPage === getLastPage()) {
return {
currentPage: 1,
currentArticles: pagedArticles(1)
};
} else {
return {
currentPage: prevState.currentPage + 1,
currentArticles: pagedArticles(prevState.currentPage + 1)
};
}
});
break;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment