Reputation: 592
I have been using onSnapshot
successfully to alert my code to changes in underlying data, as in
// Set up to listen for changes to the "figures" collection, that is,
// someone has created a new figure that we will want to list on the screen.
setFiguresListener: function () {
// `figuresCR` is a collection reference defined elsewhere
return this.figuresCR.onSnapshot((iFigs) => {
iFigs.forEach((fSnap) => {
const aFigure = figureConverter.fromFirestore(fSnap, null);
const dbid = aFigure.guts.dbid; // ID of the "figure" in the database
nos2.theFigures[dbid] = aFigure; // update the local copy of the data
});
nos2.ui.update();
console.log(` Listener gets ${iFigs.size} figures`);
});
But I now read about on
in the docs. It explains:
[The
on()
function] Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Use
off( )
to stop receiving updates. See Retrieve Data on the Web for more details.
The syntax is a bit different, and on()
seems to do much the same as onSnapshot()
.
So what is the real difference? Should we be using on()
instead of onSnapshot()
?
Upvotes: 2
Views: 772
Reputation: 592
Other tyros who fall into this tar pit: in the API doc pages, you might think that since firestore is a database under firebase, you could look for help under firebase.database
. But no: look only in the next section, firebase.firestore
.
Upvotes: 0
Reputation: 317372
on()
is an operation for reading from Firebase Realtime Database. That's a completely different database with different APIs than Firestore. They have essentially no overlap. There is no on()
operation with Firestore.
If you're working with Firestore, ignore all the documentation about Realtime Database, and stick to using onSnapshot()
for getting realtime updates.
Upvotes: 1