0
0
Firebasecloud~10 mins

Transaction read-then-write pattern in Firebase - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to start a transaction in Firebase.

Firebase
const result = await db.runTransaction(async (transaction) => {
  const doc = await transaction.get([1]);
  // ...
});
Drag options to blanks, or click blank then click option'
AdbRef
BtransactionRef
CdocRef
DrefDoc
Attempts:
3 left
💡 Hint
Common Mistakes
Using a collection reference instead of a document reference.
Passing the transaction object itself.
2fill in blank
medium

Complete the code to check if the document exists inside the transaction.

Firebase
if (!doc.exists) {
  throw new Error([1]);
}
Drag options to blanks, or click blank then click option'
A"Document does not exist"
BDocument does not exist
CdocRef
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the error message string.
Passing a variable instead of a string.
3fill in blank
hard

Fix the error in the transaction update call to correctly update the document.

Firebase
transaction.[1](docRef, { count: doc.data().count + 1 });
Drag options to blanks, or click blank then click option'
Aupdate
Bset
Cwrite
Dmodify
Attempts:
3 left
💡 Hint
Common Mistakes
Using set which overwrites the whole document.
Using non-existent methods like write or modify.
4fill in blank
hard

Fill both blanks to correctly read and update a user's score inside a transaction.

Firebase
const doc = await transaction.[1](userRef);
transaction.[2](userRef, { score: (doc.data().score || 0) + 10 });
Drag options to blanks, or click blank then click option'
Aget
Bupdate
Cset
Dwrite
Attempts:
3 left
💡 Hint
Common Mistakes
Using set instead of update which overwrites the document.
Using write which is not a valid method.
5fill in blank
hard

Fill all three blanks to complete a transaction that increments a product's stock count safely.

Firebase
const productDoc = await transaction.[1](productRef);
if (!productDoc.exists) {
  throw new Error([2]);
}
transaction.[3](productRef, { stock: productDoc.data().stock + 1 });
Drag options to blanks, or click blank then click option'
Aget
B"Product does not exist"
Cupdate
Dset
Attempts:
3 left
💡 Hint
Common Mistakes
Using set instead of update which overwrites the document.
Throwing an error without quotes around the message.
Trying to update before reading the document.