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.
I need some help. Thank you