javascriptfirebasegoogle-cloud-firestorereact-native-firebase

When I use where in react native firestore, startAfter returns an empty array


 
const animalsData = [];
  let snapshot = null;
  try {
    if (!lastVisible) {
      snapshot = await firestore()
        .collection("animals")
        .where("species", '==', selectedType)
        .orderBy('timestamp', 'desc')
        .limit(7)
        .get();
    } else {
     
      snapshot = await firestore()
        .collection("animals")
        .where("species", '==', selectedType)
        .orderBy('timestamp', 'desc')
        .startAfter(lastDoc)
        .limit(7)
        .get();
    }

The issue arises when I add the .where("species", '==', selectedType) condition. The initial query works fine and returns the expected results. However, when trying to fetch the next set of data (i.e., implementing pagination), the query returns an empty array, even though there are more documents that should match the criteria.

Some additional context:

I'm unsure why the addition of the .where filter causes subsequent queries to return an empty array. I've done considerable research but haven't found a solution that addresses this specific issue.

Any insights or suggestions on how to resolve this would be greatly appreciated. Thank you!


Solution

  • For every query you want to execute on Firestore, it needs to have a index (or combination of indexes) that it can use to check the conditions in that query. When your query filters/orders only on a single field, the index typically exists by default - as Firestore creates single-field indexes automatically. But when you add additional fields to filter/order on, you usually need a composite index - and those you'll have to create explicitly yourself.

    On most clients, the SDK will raise an error when an index is missing. If you catch and log this error, it contains a URL that links directly to the Firestore console where you can create the index with a single click (and some patience). For more on this, see the Firestore documentation on creating a missing index through an error message. Alternatively you can create the index in the Firebase console from scratch.