Home > Enterprise >  how to handle a promise in firebase query when there is an if statement
how to handle a promise in firebase query when there is an if statement

Time:07-17

I try to loop through all my documents and check if there is a matching between an object Id and my id then push the data into an array , my problem is that I can not get back any data my array is always empty here is my code :

   let d = []
   let b;
    const all = await db.collection('cars')
    .get()
       .then(documentSnapshot  => 
          {  if (!documentSnapshot.empty) {
              documentSnapshot.map(async (doc) => {
                         idd = await doc.data().user.id;
                         if(idd == 'myid'){
                           b = doc.data();
                           d.push(b) 
                       }
              
              });
          }
          }
          );

      return  Promise.all(all).then(() => setActiveSpinner(false), setThereIsData(true)).catch(e => console.log(e))

CodePudding user response:

You have different issues within your implementation.

First, you are mixing both plain Promise objects with callback handlers along with async/await imperative usage which usually leads to un-wanted program behavior.

You are miss-collecting the different matching documents using the Array.prototype.map operator without neither returning a result for each element nor for the transformed result.

Here down a trimmed implementation using the async/await pattern:

const result = [];
const querySnapshots = await db.collection('cars').get();
for (const document of querySnapshots) {
  const data = document.data();
  if (data.user.id === 'myid') {
    result.push(b);
  }
}
setActiveSpinner(false);
setThereIsData(true);
return result;
  • Related