egwang
egwang

Reputation: 33

Firebase Paginate

I made the code below referring to the pagination document of FIREBASE.

( https://firebase.google.com/docs/firestore/query-data/query-cursors#web-v8_3 )

I know that 'limit(3)' prints 3 documents, but I don't know how to use the 'next' and 'last' variables.

What I want to implement is to show three of my posts per page and move to the next page when the button is pressed.

Since I just started web development, everything is difficult. please help me


var first = db.collection('product').orderBy('date').limit(3);

var paginate = first.get().then((snapshot)=>{
    snapshot.forEach((doc) => {
      console.log(doc.id);
      var summary = doc.data().content.slice(0,50);
      var template = `<div class="product">
        <div class="thumbnail" style="background-image: url('${doc.data().image}')"></div>
        <div class="flex-grow-1 p-4">
          <h5 class="title"><a href= "/detail.html?id=${doc.id}">${doc.data().title}</a></h5>
          <p class="date">${doc.data().date.toDate()}</p>
          <p class = "summary">${summary}</p>
        </div>
      </div>
      <hr>`;  
      $('.container').append(template);
    })

Upvotes: 3

Views: 244

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50840

You can try this function:

let lastDocSnap = null

async function getNextPage(lastDoc) {
  let ref = db.collection('product').orderBy('date')
  
  // Check if there is previos snapshot available
  if (lastDoc) ref = ref.startAfter(lastDoc)
  const snapshot = await ref.limit(3).get()

  // Set new last snapshot
  lastDocSnapshot = snapshot.docs[snapshot.size - 1]

  // return data
  return snapshot.docs.map(d => d.data())
}

While calling this function, pass the lastDocSnap as a param:

getNextPage().then((docs) => {
  docs.forEach((doc) => {
    // doc itself is the data of document here
    // Hence .data() is removed from original code

    console.log(doc.id);
    var summary = doc.content.slice(0,50);
    var template = `<div class="product">
        <div class="thumbnail" style="background-image: url('${doc.image}')"></div>
        <div class="flex-grow-1 p-4">
          <h5 class="title"><a href= "/detail.html?id=${doc.id}">${doc.title}</a></h5>
          <p class="date">${doc.date.toDate()}</p>
          <p class = "summary">${summary}</p>
        </div>
      </div>
      <hr>`;  
      $('.container').append(template);
  })
})

Call this function at page load (as lastDocSnap will be null, it'll fetch first 3 docs). Call the same function when user clicks 'next' but this time as we have lastDocSnap, the startAfter method will be added to the query. This essentially means the query will first order the document by date and then fetch 3 documents after the document you pass in startAfter

Upvotes: 2

Related Questions