Using Firestore Web API v9, suppose I have a collection listener and a document listener for a document in that collection. An update for that document comes through.
Two questions:
Example:
collectionSnapshots(collection(firestore, 'people')).subscribe(...);
docSnapshots(doc(firestore, 'people/john')).subscribe(...);
Am I charged for two reads?
You are charged for number of documents being read irrespective of number of listeners you have. If 'people' collection has 50 documents and the listener returns 50 docs, you are charged 50 reads. Any updates received later will be charged 1 read per update.
Does the SDK send the data back twice, or send it once and dispatch an update twice?
When the listener is added, it'll return all documents that matched your query (in this case, the complete people collection). After that, whenever a document is added/updated/deleted the update will be received by listener.
Yes, if you have a listener on people collection and another listener on a document of that collection. Both the listeners will fetch updated data and you'll be charged 2 reads for that single update. You don't need another listener just for a single document though. You can read document ID from changes received and update it in your web app.
import { collection, query, where, onSnapshot } from "firebase/firestore";
const q = query(collection(db, "people"));
const unsubscribe = onSnapshot(q, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === "modified") {
// a document in people collection is modified
const docId = change.doc.id;
const docData = change.doc.data();
}
});
});