I experienced this scenario when a new data is added in my Firebase Firestore Database.
forEach will iterate the values of the Document (Firebase Document) while the ngFor will rendered the data in frontend. This duplication of data will only happen if the page is not reloaded and when a new data is added, if user reloads the pages, the duplication stops.
My wild guess here, it can be solved if the page can reload automatically but unfortunately the adding of data happens in other pages.
This is the image to understand more: (If you noticed, some of the data was duplicated in frontend but if the user reloads the page, it will go back to normal).

home.html
<div *ngIf="!auth.canDelete(user)">
<ion-grid>
<ion-row>
<ion-col size-lg="3" size-md="4" size-sm="6" size="12" *ngFor="let o of orgInfo">
<ion-card>
<div >
<ion-img [src]="o.imageUrl"></ion-img>
</div>
<ion-card-header>
<ion-card-title >{{ o.orgName }}</ion-card-title>
<ion-card-subtitle>{{ o.userList?.length > 0 ? o.userList?.length : '0' }} member/s</ion-card-subtitle>
</ion-card-header>
<ion-card-content>
<p >{{ o.description }}</p>
</ion-card-content>
<ion-button fill="solid" expand="block" color="primary" [routerLink]="['/home', o.orgId]">
<ion-icon name="open" slot="start"></ion-icon>
<ion-label>View</ion-label>
</ion-button>
</ion-card>
</ion-col>
</ion-row>
</ion-grid>
</div>
home.ts
this.organizationList.forEach(uid => {
const docRef = firebase.firestore().collection("organization").doc(uid);
docRef.get().then((doc) => {
if (doc.exists) {
this.orgInfo.push({
orgId: doc.data().orgId,
orgName: doc.data().orgName,
description: doc.data().description,
imageUrl: doc.data().imageUrl,
userList: doc.data().userList
});
this.orgInfo.sort((a, b) => (a.userName > b.userName) ? 1 : -1);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});
});
CodePudding user response:
If you have a unique value that doc.data() returns, you can check if the orgInfo array already contains an object with such value, and push to orgInfo only if there's no such object:
if (doc.exists) {
// assumption: doc.data().orgId is a unique value:
if (!this.orgInfo.some(e => e.orgId === doc.data().orgId)) {
// this.orgInfo doesn't contain the item, so we can add it:
this.orgInfo.push({...});
}
}
