0
0
Firebasecloud~30 mins

Transaction basics in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Transaction basics
📖 Scenario: You are building a simple inventory system using Firebase Realtime Database. You want to safely update the stock count of a product when a purchase happens, ensuring no conflicts if multiple users buy at the same time.
🎯 Goal: Build a Firebase transaction that reads the current stock of a product, decreases it by the purchased amount only if enough stock exists, and writes the updated stock back safely.
📋 What You'll Learn
Create a reference to the product stock in Firebase Realtime Database
Set a purchase amount variable
Use a Firebase transaction to update the stock safely
Complete the transaction with proper success handling
💡 Why This Matters
🌍 Real World
Inventory systems need to update stock counts safely when multiple users buy items at the same time. Firebase transactions help prevent conflicts and data corruption.
💼 Career
Understanding Firebase transactions is important for developers building real-time apps that require safe concurrent updates to shared data.
Progress0 / 4 steps
1
Create a Firebase reference to product stock
Create a variable called productStockRef that references the path 'products/product123/stock' in the Firebase Realtime Database using firebase.database().ref().
Firebase
Need a hint?

Use firebase.database().ref('path') to create a reference to a location in the database.

2
Set the purchase amount variable
Create a variable called purchaseAmount and set it to 3 to represent the number of items being bought.
Firebase
Need a hint?

Just create a constant variable with the number 3.

3
Use a Firebase transaction to update stock safely
Call productStockRef.transaction with a function that takes the current stock value as currentStock. Inside the function, if currentStock is null, return null. If currentStock is less than purchaseAmount, return undefined to abort. Otherwise, return currentStock - purchaseAmount.
Firebase
Need a hint?

The transaction function receives the current value. Return the new value or undefined to abort.

4
Complete the transaction with success handling
Add a second argument to productStockRef.transaction which is a callback function with parameters error, committed, and snapshot. Inside the callback, if error exists, handle it (for example, log it). If committed is true, the transaction succeeded. Use snapshot.val() to get the updated stock.
Firebase
Need a hint?

The second argument to transaction is a callback for completion status.