Firebase V9 Firestore Get Document Data With Real-Time Updates
Learn how to get document data with real-time updates using the onSnapshot() method from Cloud Firestore in Firebase version 9.
- Get Documents With Real-Time Updates Using onSnapshot() → you’re here
- Get Documents From A Collection Once using getDocs()
- Get Document By ID
The sample Firestore Database has a cities collection that has two documents in it, like in the screenshot below.
Nothing fancy.

Let’s get all the documents of the cities collection using the onSnapshot() method.
To do that we need three Firebase methods:
- getFirestore()
- collection()
- onSnapshot()
Import Firestore Database and de-structure the three methods.
import { getFirestore, collection, onSnapshot } from "https://www.gstatic.com/firebasejs/9.9.3/firebase-firestore.js";
Then create an instance of the Firestore Database by calling the getFirestore() method and assign it to a constant db.
const db = getFirestore();
After that, create a database and collection references by calling the collection() method passing two arguments, which are:
- db: Firestore Database
- cities: Which is the collection name where we’re going to get data from
const dbRef = collection(db, "cities");
Finally, call the onSnapshot() method to get data from the cities collection.
The onSnapshot() method takes two arguments:
- dbRef which is a database/collection reference.
- The anonymous callback function will have data from the cities collection as a snapshot object, named docSnap in this case.
The snapshot object is an array-type object that has all the documents as Javascript objects along with other metadata.
onSnapshot(dbRef, docsSnap => {
docsSnap.forEach(doc => {
console.log(doc.data());
})
});
Loop through the snapshot object using the forEach() method.
The forEach() function will also take an anonymous callback function, with a parameter doc, in which we can get a document one by one stored in the cities collection on each iteration.
This is very similar to the getDocs() method..right?
With the getDocs() method, if there is any change in the Firestore Database, you’ll need to refresh the browser in order to see the new changes.
On the other hand, the onSnapshot() method listens for any changes on the Firestore Database and updates the front end automatically without refreshing the page.

Here is the full code:
import { getFirestore, collection, onSnapshot } from "https://www.gstatic.com/firebasejs/9.9.3/firebase-firestore.js";
const db = getFirestore();
const dbRef = collection(db, "cities");
onSnapshot(dbRef, docsSnap => {
docsSnap.forEach(doc => {
console.log(doc.data());
})
});