/firebase-tutorials

How to perform transactions in Firestore?

Learn how to perform atomic transactions in Firestore for web and Android apps, ensuring reliable data consistency with our step-by-step guide.

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 perform transactions in Firestore?

 

Introduction

Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud. Transactions in Firestore allow you to perform multiple read and write operations atomically. This ensures that either all modifications occur, or none do, in scenarios where data consistency is critical.

 

Step 1: Set Up Firestore in Your Project

 

To perform transactions in Firestore, you first need to set it up in your project. This typically involves:

  • Adding Firebase to your app:

    
      // Include Firebase SDK in your project
      // For the web:
      <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
      <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
      
      // Initialize Firebase
      firebase.initializeApp({
        apiKey: "YOUR_API_KEY",
        authDomain: "YOUR_AUTH_DOMAIN",
        projectId: "YOUR_PROJECT_ID"
      });
      
      // Initialize Firestore through Firebase
      const db = firebase.firestore();
    
  • Ensure you have configured Firebase in your Android or iOS app as per the Firebase documentation.

 

Step 2: Understand Firestore Transaction Flow

 

Firestore transactions are used for batch reads and writes, with the guarantee that all or none of the operations are executed. The flow for using transactions typically involves:

  • Starting a transaction.
  • Reading values within the transaction.
  • Performing write operations.
  • Committing the transaction if no errors occur.

 

Step 3: Implement Firestore Transaction in JavaScript

 

Below is a sample implementation of a Firestore transaction using JavaScript. Ensure that you have initialized Firestore as shown in Step 1.


// Define an async function to run the transaction
async function performTransaction() {
  const docRef = db.collection('yourCollection').doc('yourDocument');

  try {
    // Run a Firestore transaction
    await db.runTransaction(async (transaction) => {
      // Perform a read operation
      const doc = await transaction.get(docRef);
      
      if (!doc.exists) {
        throw new Error("Document does not exist!");
      }
      
      // Decide what calculation or change you may need
      const newValue = doc.data().field + 1;

      // Perform a write operation
      transaction.update(docRef, { field: newValue });
    });
    console.log("Transaction successfully committed!");
  } catch (error) {
    console.error("Transaction failed: ", error);
  }
}

// Call the function to perform the transaction
performTransaction();
  

Replace 'yourCollection', 'yourDocument', and 'field' with your specific collection name, document ID, and field name. This code reads a field value, increments it, and updates it inside a transaction.

 

Step 4: Implement Firestore Transaction in Java (For Android)

 

Use the following code snippet to implement a transaction in an Android application:


FirebaseFirestore db = FirebaseFirestore.getInstance();

DocumentReference docRef = db.collection("yourCollection").document("yourDocument");

db.runTransaction((Transaction.Function) transaction -> {
  // Read the document and get its current value
  DocumentSnapshot snapshot = transaction.get(docRef);
  Long newValue = snapshot.getLong("field") + 1;

  // Update the document
  transaction.update(docRef, "field", newValue);

  // Success
  return null;
}).addOnSuccessListener(aVoid -> {
  Log.d(TAG, "Transaction success!");
}).addOnFailureListener(e -> {
  Log.w(TAG, "Transaction failure.", e);
});
  

Replace "yourCollection", "yourDocument", and "field" with your collection name, document ID, and field name.

 

Conclusion

 

Firestore transactions are an essential part of managing consistent and reliable updates to your Firestore collections and documents. By following these steps, you can confidently implement transactions in your web or Android applications using Firebase Firestore. For more advanced transaction capabilities, consult the Firebase and Firestore documentation.

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