Skip to content

Firestore Pagination – Code Template cho phân trang

Dùng limit() & start()

trong start() sẽ nhận argument là 1 doc

  • startAt() or startAfter()
  •  endAt() or endBefore()

startAt(A) in a query, it returns the entire alphabet

startAfter(A) instead, it returns B-Z

var first = db.collection("cities")
        .orderBy("population")
        .limit(25);

return first.get().then(function (documentSnapshots) {

  var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
  console.log("last", lastVisible);

  var next = db.collection("cities")
          .orderBy("population")
          .startAfter(lastVisible)
          .limit(25);
});

Implementation

<div class="load-more">
    <button>Load More</button>
</div>

// html

Click Pagination

const container = document.querySelector(".container");

// store last document
let lastestDoc = null;

const getNextReviews = async function() {
    const ref = db.collection('reviews')
        .orderBy("createdAt")
        .startAfter(lastestDoc || 0)
        .limit(6);
    const data = await ref.get();

    if(data.empty) {
        console.log("No more data to bring up !")
        return;
    }

    // update lastest doc
    lastestDoc = data.docs[data.docs.length - 1];

    let template = "";
    data.docs.forEach(doc => {
        const review = doc.data();
        template += `
            <div class="card">
                <h2>${review.title}</h2>
                <p>Writtern by ${review.author}</p>
                <p>Rating -  ${review.rating} / 5</p>
            </div>
        `
    })

    container.innerHTML = template;
}

window.addEventListener("DOMContentLoaded", () => getNextReviews());

const loadMore = document.querySelector(".load-more button");

const handleClick = () => { getNextReviews() }

loadMore.addEventListener("click", handleClick);

Scroll Pagination

Javascript

Published inFirestore

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *