i do an ngFor on a list and i show a table with multiple recordings. I have in my ts two methods, one for getAll and one for delete which are listed bellow:
HTML:
<tr *ngFor="let value of imagesList">
<td scope="row">{{value.id}}</td>
<td>{{value.imageName}}</td>
<td>{{value.warDate | date}}</td>
<td><img src="{{value.screen}}" width="40px" height="40px" class="rounded-circle"></td>
<td> {{"dashboard.Download" | translate}}</a> </td>
<td><button type="button" class="btn btn-link" (click)="deleteWar(value)">{{"dashboard.Delete" | translate}}</button></td>
</tr>
GET:
getAllUploadedImages() {
const auth = getAuth();
const user = auth.currentUser;
const q = query(collection(this.db, "warstats"), where("userId", "==", user?.uid));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
querySnapshot.forEach((doc) => {
const data = doc.data() as WarImage;
data.id = doc.id;
this.imagesList.push(data as WarImage);
});
});
}
DELETE:
async deleteWar(image: WarImage) {
await deleteDoc(doc(this.db, '/warstats/' + image.id));
}
The problem that i encounter is like this:
If have 3 items in the list and i delete 1 .. the list auto updates .. but instead of updating with 2 items it updates with 5 items .. ( the 3 that i had + the two taht remains after delete ) .. if i refresh the page, works good showing only the 2 remaining items.
Thank you in advance.
2
Answers
It is possible that the problem is that you push the list every time you do a get, which adds the new data to what was already in the array. Try removing the contents of the array before saving the new data each time you do a get. I hope I’ve helped!
you should clear the imagesList array before adding the new data. You can modify your code
Also, remember to unsubscribe from the snapshot listener when the component is destroyed
With these changes, your list should update correctly when an item is deleted, showing only the remaining items without the need to refresh the page.