Hey guys, I’m building a blog site and trying to use pagination to display different pages of blog posts when there are more than 3 posts stored in the database. I’m trying to pass data from the front-end when pushing “newer” or “previous” buttons to the back-end to control the direction of the pages. How can I go about doing that?
What I want to do is pass data from the front-end buttons up top to the route below so that the currentPage
variable will increment or decrement. From there, it will render the appropriate posts depending on which direction the user clicks. I tried testing it by manipulating the currentPage
variable manually and it works. I just need help on how to control that from the buttons on the front-end. I hope I’m making sense.
Any help would be greatly appreciated.
This is the code in the front-end that controls the “next” and “previous” buttons.
<% if(totalItems > 3){ %>
<div class="page-buttons">
<form action="/">
<button type="submit" class="btn btn-outline-info newer-posts">Next</button>
<button type="submit" class="btn btn-outline-info older-posts">Previous</button>
</form>
</div>
<% } %>
Here is the route that handles displaying the posts.
app.get("/", (req, res) => {
let currentPage = 1;
let perPage = 3;
let totalItems;
Post.find()
.countDocuments()
.then(count => {
totalItems = count;
Post.find()
.skip((currentPage - 1) * perPage)
.limit(perPage)
.then(posts => {
res.render("home", {
posts: posts,
totalItems: totalItems,
currentPage: currentPage
});
});
})
});