/firebase-tutorials

How to listen to real-time updates in Firestore?

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

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to listen to real-time updates in Firestore?

 

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

 

  • Plan and create your Firestore database collections and documents from the Firebase Console.
  • For instance, you can create a 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

 

  • Finally, add and modify documents in your Firestore from the console or through code to test your real-time listeners.
  • Ensure your application logs or updates the UI as per the changes made in Firestore.

 

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.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022