Firestore query cursor always returning same data

192 Views Asked by At

I'm working on a virtualized table that lazily subscribes to a new batch of items in firestore. The issue is that query cursor returns the same batch of data, regardless of the startAt index being different.

const subscribeForItems = (
  startIndex: number,
  handleItems: (items: FirestoreItem[]) => void,
): (() => void) => {

  const firestoreQuery = query(
    collection(firestore, RootCollections.Items),
    orderBy('price'),
    startAt(startIndex),
    limit(LIMIT),
  );

  return onSnapshot(firestoreQuery, (querySnapshot) => {
    const items: FirestoreItem[] = [];

    querySnapshot.forEach((doc) => {
      items.unshift(
        FirestoreUtils.extractDocumentData<FirestoreItem>(doc),
      );
    });

    console.log(startIndex)// START INDEX IS DIFFERENT HERE EACH INVOCATION
    console.log(items)// ITEMS ARE SAME HERE EACH INVOCATION (AS IF I'M ALWAYS PASSING THE SAME START INDEX)

    handleItems(items);
  });
};
1

There are 1 best solutions below

0
Damjan On

So the issue was setting the limit. Instead of

const firestoreQuery = query(
    collection(firestore, RootCollections.Items),
    orderBy('price'),
    startAt(startIndex),
    limit(LIMIT),
  );

it should be

const firestoreQuery = query(
    collection(firestore, RootCollections.Items),
    orderBy('price'),
    startAt(startIndex),
    limit(LIMIT + startIndex),
  );

I find limit() method to be named counterintuitively, perhaps endAt() would have been a better name, if I need to do the addition myself