C. Ardayfio
C. Ardayfio

Reputation: 85

Can't implement pagination in firebase website

Intenteded Functionality

I would like to be able to have pagination on my website. The way it'd work is that users would view the first 10 questions on the main page, then they could click a button to flip to the next page to see the next 10 questions. They should also be able to go in the reverse direction as well.

Method

Presumably, it'd be best to have two parameters in my listenForQuestions function called pageNumber and pageLength. pageLnegth would be the number of questions to display on a given page and pageNumber would be the actual page number to go to. I tried using startAt, but this doesn't takes an actual value to limit by rather than just by limiting to the first n results of the query as I would want.

import { getAuth } from '@firebase/auth';
import {
  collection,
  doc,
  getDoc,
  getFirestore, limit, onSnapshot,
  orderBy,
  query,
  where,
  startAt,
  endAt
} from '@firebase/firestore';

export function listenForQuestions(options, callback) {
  let filters = [
        where('answerAccepted', '==', false),
        orderBy('bounty', 'desc'),
        orderBy('postedTimestamp', 'desc'),
    ];
     
  // filters.push(startAt(0), endAt(10)) // This doesn't seem to work???
  onSnapshot(
    query(collection(getFirestore(), 'questions'), ...filters),
    (snapshot) => {
      callback(snapshot.docs.map((doc) => doc.data()));
    }
  );
}

Upvotes: 0

Views: 440

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598765

Firestore pagination isn't based on offsets, but rather on a cursor - typically last item of the previous page. I recommend checking out the Firestore documentation on pagination with cursors or some of the previous questions on the pagination with firestore.

Upvotes: 1

Related Questions