My expectation is to observe the changes of my collection only when there is a WRITE/DELETE action. By doing some search I understood onSnapshot() method does that. But this method unexpectedly is being called when I’m reading my documents by getDocs().
Here is my code:
// Firestore instance is defined and collection reference is accessible
const db = getFirestore();
const todosCollection = collection(db, 'todos');
// For the sake of testing I even tried to stop the observer at the fetch method by using a boolean variable
let areTodosFetched = false;
function onTodosChange() {
if (!areTodosFetched) {
console.log('should return');
return;
}
onSnapshot(todosCollection, (snapShot) => {
snapShot.docChanges().forEach((change) => {
if (change.type === 'added') {
// The code drops in this block!
console.log('New todo: ', change.doc.id);
}
if (change.type === 'modified') {
console.log('Modified todo: ', change.doc.id);
}
if (change.type === 'removed') {
console.log('Removed todo: ', change.doc.id);
}
});
});
}
async function getTodos() {
try {
await getDocs(todosCollection);
areTodosFetched = true;
}
catch (error) {
console.error('Error getting documents: ', error);
}
}
// In a component I'm executing them
await getTodos();
onTodosChange();
I removed all side effects of getTodos() method and I’m only calling await getDocs(todosCollection);
But still the observer is being called.