Discover how to set up Firebase, initialize Firestore, and use onSnapshot to listen for real-time data updates in your application.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up Your Firebase Project
Before you begin, ensure you have a Firebase account. Visit the Firebase Console and create a new project.
Enable Firestore from the Database option in your Firebase console.
Install the Firebase SDK in your application. For web applications, you can add Firebase using npm:
```html
npm install firebase
```
Or include Firebase in your HTML directly via a CDN:
```html
```
Step 2: Initialize Firebase in Your App
To initialize Firebase, use the following code. Replace firebaseConfig with your project's configuration details from the Firebase console.
```html
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "YOUR-API-KEY",
authDomain: "YOUR-PROJECT-ID.firebaseapp.com",
projectId: "YOUR-PROJECT-ID",
storageBucket: "YOUR-PROJECT-ID.appspot.com",
messagingSenderId: "YOUR-MESSAGING-SENDER-ID",
appId: "YOUR-APP-ID"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
```
Step 3: Set Up Firestore Data Structure
users collection with documents representing each user having fields like name, email, etc.
Step 4: Listen to Real-Time Updates
Use Firestore's onSnapshot method to listen for updates in real time. This will update your application whenever data in the Firestore changes.
```html
import { collection, onSnapshot } from "firebase/firestore";
const usersCollection = collection(db, "users");
onSnapshot(usersCollection, (snapshot) => {
snapshot.docs.forEach(doc => {
console.log(doc.data());
});
});
```
Step 5: Handle Real-Time Data
With real-time updates, you can update the UI or data state in your application. Use the onSnapshot callback function to respond to different events like added, modified, or removed documents.
```html
onSnapshot(usersCollection, (snapshot) => {
snapshot.docChanges().forEach(change => {
if (change.type === "added") {
console.log("New user: ", change.doc.data());
}
if (change.type === "modified") {
console.log("Modified user: ", change.doc.data());
}
if (change.type === "removed") {
console.log("Removed user: ", change.doc.data());
}
});
});
```
Step 6: Test the Real-Time Listener
By following these steps, you can effectively listen to real-time updates in Firestore and ensure your applications are always in sync with your database.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.