0

I am building an application in Angular8 that uses firebase's realtime database. I have a list of products that I want to add to the database but everytime I do, I need to know if this product is not already added in. The isssue occurs when I check for if the snapshot.exists() in the loop, it always returns false since firebase set method is asynchronous and the call to set function has not yet completed but the loop has continued on with the next iteration.

this.csvData.forEach(product => {
    this.database.database
    .ref(`products/${product.Company}`)
    .once('value', (snapshot) => {
      if (snapshot.exists()) {
        latestIndex = snapshot.numChildren(); 
          this.database.database
          .ref()
          .child('/products')
          .child('/'+product.Company+'/'+ latestIndex)
          .set(product)
          .then(() => {
            // Success 
          })
          .catch(error => {
              // Error
          }); 
      } else {
        //latestIndex = snapshot.numChildren();
        this.database.database
        .ref()
        .child('/products')
        .child('/'+product.Company+'/'+'0')
        .set(product)
        .then(() => {
          // Success 
        })
        .catch(error => {
            // Error
        });          
      } 
    }); // Ends if snapshot doesnt exitts
  }); //foreach ends

I am also attaching a screenshot of the single object of product that I have. enter image description here

I need some help. Thank you

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Osama Khawar
  • 74
  • 1
  • 6
  • If you want a key like that you'll need to use transactions. Those will hurt both scalability/concurrency and the offline behavior of your app, which is why I'd highly recommend using Firebase's built-in `push()` primitive instead. See https://stackoverflow.com/questions/39519021/how-to-create-auto-incremented-key-in-firebase – Frank van Puffelen Feb 20 '20 at 23:08
  • Hello @FrankvanPuffelen. The problem is not with the key but the firebase action taking longer and foreach loop continuing execution. I will also try with push but I think the problem will still persist. I was looking for a better way like promises to deal with this but somehow I can't seem to wrap my head around it. – Osama Khawar Feb 21 '20 at 06:40
  • That sounds like you want to use `Promise.all()` to wait until all the database calls are done. See https://stackoverflow.com/search?q=%5Bfirebase-realtime-database%5D+promise.all for some examples of that. – Frank van Puffelen Feb 21 '20 at 14:54

0 Answers0