0
0
Firebasecloud~30 mins

Transaction read-then-write pattern in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Transaction read-then-write pattern
📖 Scenario: You are building a simple inventory system using Firebase Realtime Database. You want to safely update the stock count of a product only if the current stock is enough to fulfill an order.
🎯 Goal: Build a Firebase transaction that reads the current stock of a product, checks if there is enough stock, and if yes, reduces the stock by the order quantity.
📋 What You'll Learn
Create a reference to the product stock in Firebase Realtime Database
Set an order quantity variable
Use a Firebase transaction to read the current stock
Inside the transaction, check if stock is enough and update it
Return the updated stock or abort the transaction if not enough stock
💡 Why This Matters
🌍 Real World
This pattern is used in inventory management systems to prevent overselling products by ensuring stock counts are updated safely even with multiple users.
💼 Career
Understanding Firebase transactions is important for developers working on real-time applications that require safe concurrent data updates.
Progress0 / 4 steps
1
Create a Firebase reference to product stock
Create a constant called productStockRef that points to the Firebase Realtime Database path 'products/product123/stock' using firebase.database().ref().
Firebase
Need a hint?

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

2
Set the order quantity variable
Create a constant called orderQuantity and set it to the number 3.
Firebase
Need a hint?

Use const orderQuantity = 3; to set the order quantity.

3
Write the transaction to read and update stock
Use productStockRef.transaction with a callback function that takes currentStock as input. Inside the function, if currentStock is null, return null. If currentStock is less than orderQuantity, return undefined to abort. Otherwise, return currentStock - orderQuantity.
Firebase
Need a hint?

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

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

The second callback handles the transaction result. Check error and committed flags.