How do I get pagination to work on my Node blog site?

Refresh

2 weeks ago

Views

6 time

0

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 pages. How can I go about doing that?

I have tried playing around the POST method but doesn't seem to work.

This is the code in the front-end that controls the "next" and "previous" buttons.

<% if(totalItems > 3){ %>
    <div class="page-buttons">

      <button class="btn btn-outline-info newer-posts" value="<%=currentPage++ %>">Next</button>

      <button class="btn btn-outline-info older-posts" value="<%= currentPage-- %>">Previous</button>
    </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
          });
        });
    })
});

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.

0 answers