I set a listener to a firebase collection like this:
useEffect(() => {
let data:IFirebaseProject[] = [];
//console.log(data);
console.log('SUBSCRIBED');
const unsubscribe = firebase
.firestore()
.collection("projects")
.onSnapshot((snapshot) => {
let changes = snapshot.docChanges();
console.log(changes); // LOG 1
changes.forEach(change => {
if (change.type === "added") {
data.push({
id: change.doc.id,
...change.doc.data()
} as IFirebaseProject);
console.log('ADDED', {...change.doc.data()}); // LOG 2
} else if (change.type === "removed") {
const removeIndex = data.map(function(project) { return project.id; }).indexOf(change.doc.id);
data.splice(removeIndex,1)
console.log('REMOVED')
}
});
setProjects([...data]);
console.log('projects set');
});
When I remove a record, console.log('REMOVED') appears once, as expected.
But when I add a record, console.log('ADDED', {...change.doc.data()}); appears for the added record, and then as many times as records were before the addition.
So if for example I got two records, and add a third, I obtain this log sequence:
I would expect to have only one change and one record added instead of as many changes as records are. The previous not added records are not added to the database, but, considered as added changes in the snapshot and merged to the state as such.
I tried two ways to link my component to firestore, with redux and with react hooks and the behaviour is the same, however this is unexpected for me, as for bigger databases doesnt seem to be very efficient and I would expect that the current database status to be chached somehow.
Is this the normal behaviour or should it be only one change when a record is added and there is something wrong with my code?
