/firebase-tutorials

How to use transactions in Realtime Database?

Step-by-step guide to using Firebase Realtime Database transactions for safe, concurrent data updates and secure app rules.

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 use transactions in Realtime Database?

 

Step 1: Set Up Firebase in Your Project

 

First, ensure that your Firebase project is set up. If you haven't, go to the Firebase Console and create a new project. Follow the setup instructions to add Firebase to your app (web, iOS, or Android). Once Firebase is added, ensure that the Realtime Database is enabled.

 

Step 2: Initialize Firebase in Your Application

 

For a web app, you typically initialize Firebase in your main JavaScript file. Make sure you replace the Firebase configuration with your own Firebase project settings.

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  databaseURL: "YOUR_DATABASE_URL",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

const app = initializeApp(firebaseConfig);
const database = getDatabase(app);

 

Step 3: Structure Your Realtime Database

 

Decide on the structure of your Realtime Database. For example, let's assume you have a users node where each user has a name, age, and balance.

{
  "users": {
    "user1": {
      "name": "John Doe",
      "age": 30,
      "balance": 100
    },
    // More users...
  }
}

 

Step 4: Implement a Transaction

 

Transactions are useful when you need to ensure that the data has not been changed by another client before you modify it. Use transactions to modify data safely by applying a function to the current state of the data. For example, let's increment a user's balance:

import { ref, runTransaction } from "firebase/database";

function incrementUserBalance(userId, incrementValue) {
  const userRef = ref(database, 'users/' + userId + '/balance');

  runTransaction(userRef, (currentBalance) => {
    if (currentBalance === null) {
      return incrementValue; // Initial balance if it was null
    }
    return currentBalance + incrementValue;
  }).then((transactionResult) => {
    if (transactionResult.committed) {
      console.log('Transaction committed successfully:', transactionResult.snapshot.val());
    } else {
      console.log('Transaction not committed.');
    }
  }).catch((error) => {
    console.log('Transaction failed: ', error);
  });
}

// Invocation Example:
incrementUserBalance("user1", 50);

 

Step 5: Handle Transaction Results

 

After invoking runTransaction, it returns a promise. Check if the transaction was committed or not using .committed. Handle errors with a .catch block to ensure any issues during the transaction are logged or resolved.

 

Step 6: Test the Transaction

 

Run your application and trigger the transaction to ensure that it is working as expected. Check the Realtime Database in the Firebase Console to see if the data has updated correctly.

 

Step 7: Review and Secure Your Database Rules

 

After setting up transactions, make sure to review and secure your database rules in the Firebase Console to prevent unauthorized access. Rules should validate data and authorize users according to your app's requirements.

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
    "users": {
      "$user_id": {
        ".validate": "newData.child('balance').val() >= 0"
      }
    }
  }
}

With these steps, you can successfully implement transactions in your Firebase Realtime Database to manage concurrent data updates efficiently and securely.

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