Process Flow - Transaction basics
Start Transaction
Read Data Snapshot
Apply Update Logic
Attempt Commit
Commit
A transaction reads data, applies changes, tries to commit, and retries if conflicts occur.
db.runTransaction(transaction => {
return transaction.get(docRef).then(doc => {
const newCount = doc.data().count + 1;
transaction.update(docRef, { count: newCount });
});
});| Step | Action | Data Read | Update Applied | Commit Attempt | Result |
|---|---|---|---|---|---|
| 1 | Start transaction | N/A | N/A | No | Transaction started |
| 2 | Read document snapshot | {"count": 5} | N/A | No | Data read successfully |
| 3 | Calculate new count | 5 | count = 6 | No | Update prepared |
| 4 | Apply update | 5 | count = 6 | No | Update staged |
| 5 | Attempt commit | 5 | count = 6 | Yes | Commit successful |
| 6 | Transaction ends | N/A | N/A | No | Transaction complete |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|
| count | undefined | 5 | 6 | 6 | 6 |
| transactionState | not started | started | update prepared | update staged | committed |
Transaction basics in Firebase: - Start transaction - Read latest data snapshot - Apply update logic - Attempt commit - If commit fails, retry transaction - Ensures atomic, consistent updates
transaction() on a database reference.ref('path').transaction(updateFunction), which is correct. Options A, B, and D use incorrect method names or call patterns.database.ref('counter').transaction(currentValue => {
if (currentValue === null) {
return 1;
} else {
return currentValue + 1;
}
});
What will be the value of 'counter' after this transaction if it was initially 5?database.ref('score').transaction(() => {
database.ref('score').set(10);
return 20;
});set(10) inside the transaction function before returning a new value, which violates the rule.database.ref('users/user1/points').transaction(currentPoints => {
// Your code here
});Pass the test and this pattern moves unknown