splurring
splurring

Reputation: 81

Firebase not updating values as fast as I want with Javascript

enter image description here

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

Answers (1)

sleepystar96
sleepystar96

Reputation: 816

You have two options:

Option 1

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)
});

Option 2

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

Related Questions