This is an Angular 6 and Firestore project. I am trying to iterate through and update each document in my articlesCollection. A click event triggers the method that does the loop. The problem is, sometimes the method loops through the collection only once. Other times it loops infinitely. Is there a problem with my method? Is there a better way to loop through and update each doc in a collection?
Edit: When I hard reload localhost:4200, the first time I trigger the method it loops through once. If I trigger the method a second time, it loops infinitely.
featureArticle(article) {
const articleArray = this.articlesCollection.snapshotChanges();
articleArray.subscribe( payload => {
payload.forEach( item => {
const ID = article.id;
const articleID = item.payload.doc.data().id;
const articleTITLE = item.payload.doc.data().title;
const articleToUpdate = this.articlesCollection.doc(`${articleID}`);
if (ID === articleID) {
articleToUpdate.update({
isFeature: true
});
} else {
articleToUpdate.update({
isFeature: false
});
}
alert(`${articleTITLE} updated`); <-- LOOPS INFINITELY
});
});
}
The template:
<ng-container *ngFor="let article of articles | async">
<div (click)="featureArticle(article)">
{{ article.title }}
</div>
</ng-container>