Reputation: 81
So I have this website, that acts like a stat sheet and when I press the -1 button, the score of the game goes down by 1. I'm using javascript to access the firebase database and then subtract the score by 1.
const docRef = doc(db, "Games", game_id);
const docSnap = await getDoc(docRef);
var score = docSnap.data().team2_score
await updateDoc(docRef, {
team2_score: score -= number
});
The issue is that if a user clicks it really fast multiple times, then Firebase doesn't do all those operations. So if a user clicks the button 5 times really fast, the Firebase database would only keep track of 4 of them. This is my issue.
Is there a way to make sure that every single one of those clicks updated in the database, even when clicked really fast?
Upvotes: 2
Views: 123
Reputation: 816
You have two options:
Use Firebase Increment: https://cloud.google.com/firestore/docs/samples/firestore-data-set-numeric-increment
const docRef = doc(db, "Games", game_id);
await updateDoc(docRef, {
team2_score: firebase.firestore.FieldValue.increment(-1)
});
Use a Transaction. https://firebase.google.com/docs/firestore/manage-data/transactions#transactions
const docRef = doc(db, "Games", game_id);
try {
const result = await db.runTransaction((transaction) => {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(docRef).then((sfDoc) => {
if (!sfDoc.exists) {
throw "Document does not exist!";
}
// Note: this could be done without a transaction
// by updating the score using FieldValue.increment()
var newScore= sfDoc.data().team2_score - 1;
transaction.update(docRef, { team2_score: newScore});
});
})
console.log("Transaction successfully committed!");
} catch(error) {
console.log("Transaction failed: ", error);
}
Upvotes: 2