Firestore pagination backwards goes to first record always

Viewed 237

I am making a simple Firestore pagination. When it goes forward works as expected, but when it should go backwards it always goes to the first record.

I have been stuck here for a while, even crammed both (forward and backward) in the same function to ease the debugging.

Edit:

Added simplified version (still the same undesired results):

async init() {
  const result = await (await firestore())
    .collection('documents')
    .limit(this.limit)
    .orderBy('createTimestamp')
    // .orderBy('userName')
    .get()
  console.log(result)
  this.lastVisible = result.docs[result.docs.length - 1]
  ;[this.firstVisible] = result.docs
  result.forEach(doc => {
    console.log('doc', doc.data())
    this.myDocuments.push(doc)
  })
},
async forward() {
  const result = await (await firestore())
    .collection('documents')
    .orderBy('createTimestamp')
    // .orderBy('userName')
    .startAfter(this.lastVisible)
    .limit(this.limit)
    .get()
  this.lastVisible = result.docs[result.docs.length - 1]
  ;[this.firstVisible] = result.docs
  if (result.empty === false)
    result.forEach(doc => {
      console.log('doc', doc.data())
      this.myDocuments.push(doc)
    })
},
async backward() {
  const result = await (await firestore())
    .collection('documents')
    .orderBy('createTimestamp')
    // .orderBy('userName')
    .endBefore(this.lastVisible)
    .limit(this.limit)
    .get()
  this.lastVisible = result.docs[result.docs.length - 1]
  ;[this.firstVisible] = result.docs
  if (result.empty === false)
    result.forEach(doc => {
      console.log('doc', doc.data())
      this.myDocuments.push(doc)
    })
},

Added the calling method:

getAllDocuments: async ({ rootState, commit }, payload) => {
const documentsDb = new DocumentsDB(`${rootState.authentication.user.id}`)
console.log('Get all documents(admin)')
console.log('payload :>> ', payload)
const { startAt, endBefore, constraints, limit } = payload
console.log('startAt :>> ', startAt)
console.log('endBefore :>> ', endBefore)
console.log('limit :>> ', limit)
const documents = await documentsDb.readWithPagination(constraints, startAt, endBefore, limit)
console.log('documents', documents)
// const documents = await documentsDb.readAllAsAdmin()
// console.log('documents: ', documents)
commit('setDocuments', documents)  },

I left the console.log() for debuging reasons.

payload :>>  {constraints: null, endBefore: "2UxB7Z1HWCmvkEcfLZ5H", startAt: null, limit: 5}constraints: nullendBefore: "2UxB7Z1HWCmvkEcfLZ5H"limit: 5startAt: null__proto__: Object

Thhe original code

async readWithPagination(constraints = null, startAt = null, endBefore = null, limit = null) {
const collectionRef = (await firestore()).collection(this.collectionPath)
let query = collectionRef
if (limit) query = query.limit(limit)
query.orderBy('createTimestamp')
if (constraints) {
  constraints.forEach(constraint => {
    query = query.where(...constraint)
  })
}
query = query.orderBy(firebase.firestore.FieldPath.documentId())
if (startAt) {
  query = query.startAfter(startAt)
}
if (endBefore) {
  query = query.endBefore(endBefore)
  console.log('query :>> ', query)
}
const formatResult = result =>
  result.docs.map(ref =>
    this.convertObjectTimestampPropertiesToDate({
      id: ref.id,
      ...ref.data(),
    })
  )
return query.get().then(formatResult)  }

Edit as requested in comments:

    dispatchPaginatedForwardDocuments(startAt = null) {
  const payload = {}
  payload.orderBy = [['createTimestamp', 'asc']]
  payload.constraints = [['status', '==', 4]]
  payload.limit = this.limit
  payload.startAt = startAt?.id || null
  this.$store.dispatch('admin/getPaginatedForwardDocuments', payload, { root: true })
},
dispatchPaginatedPrevDocuments() {
  const payload = {}
  payload.orderBy = [['createTimestamp', 'asc']]
  payload.constraints = [['status', '==', 4]]
  payload.limit = this.limit
  payload.startAt = this.lastDocument.id
  payload.endBefore = this.firstDocument.id
  this.$store.dispatch('admin/getPaginatedBackwardsDocuments', payload, { root: true })
},

And this:

import UserDocumentsDB from '@/firebase/user-documents-db'
// import UsersDB from '@/firebase/users-db'
import DocumentsDB from '@/firebase/documents-db'
import { storage } from 'firebase'

export default {



// Fetch documents with pagination forwards and constraints

  // This works as expected
  getPaginatedForwardDocuments: async ({ rootState, commit }, payload) => {
    const documentsDb = new DocumentsDB(`${rootState.authentication.user.id}`)
    const documents = await documentsDb.readPaginatedForward(payload)
    console.log('documents: ', documents)
    commit('setDocuments', documents)
  },

  
   // Fetch documents with pagination backwards and constraints
   
  getPaginatedBackwardsDocuments: async ({ rootState, commit }, payload) => {
    console.log('getPaginatedBackwardsDocuments', payload)
    const documentsDb = new DocumentsDB(`${rootState.authentication.user.id}`)
    const documents = await documentsDb.readPaginatedBackwards(payload)
    console.log('documents: ', documents)
    commit('setDocuments', documents)
  },
0 Answers
Related