warCommander
warCommander

Reputation: 449

A firestore query not working in react-native

I am using react-native and I want to get specific data so I used a query, the problem is that it didn't work, but if I remove the where and do an if statement it works. How can I fix this ?

This is my implementation:

let query = firestore().collection('conversations');
query = query.where('users', 'array-contains', myId);
// query = query.where('postId', '==', postId);
query
  .orderBy('timestamp', 'desc')
  .limit(limit)
  .get()
  .then((snapshot) => {
    const offersObjects = {};
    if (snapshot.docs.length) {
      snapshot.docs.forEach((doc) => {
        if (postId === doc.data().postId) {
          offersObjects[doc.id] = { ...doc.data(), pendingMessages: [] };
        }
      });
      dispatch({
        type: chatTypes.SET_OFFERS,
        payload: { offers: offersObjects },
      });
    }
  })

Where the code is commented is where this query doesn't work which is weird since the one above it works fine. How can I fix this ?

Upvotes: 0

Views: 509

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599996

If you have more than one condition on a query, it may need a composite index that is not automatically created. If that is the case, executing the query (e.g. by calling get() on it) will raise an error, but you'r not hancling errors. I recommend adding a catch clause after your then and logging the error.

If the problem is caused by a missing index, the error message contains a URL that opens the Firebase console on the page to create the exact index that is needed, with all fields already filled in. Create the index, wait for it to be completely created, and run the query again.

Upvotes: 1

Related Questions