I am working with a firebase collection named 'messages', where I add documents as follows:
this.afs.collection('messages').add({ 'qn': message, 'student': this.student, 'upvotes': this.upvote });
The upvotes field is controlled by an upvote or downvote button. Whenever one of them is clicked, I trigger this method:
increment(messageId) { //decrement(messageId) for the downvote button
this.upvote += 1; //-=1 for the downvote button
this.messageDoc = this.afs.doc('messages/' + messageId);
this.message = this.messageDoc.valueChanges();
this.afs.doc('messages/' + messageId).update({
upvotes: this.upvote
});
}
The issue here is that I initialized the upvotes variable like this: private upvote: number = 0;
As a result, if I refresh the page and click the upvote or downvote buttons, the value will simply start from 0 again, because the upvote variable does not store the actual database value. To address this, I want to assign the data from the upvotes field in the document to the upvote variable - how can I achieve this?
Edit: I managed to resolve this problem using the following solution:
increment(messageId) {
this.upvote += 1;
let self = this;
let messageDoc = firebase.firestore().collection('messages').doc(messageId);
return firebase.firestore().runTransaction(function (transaction) {
return transaction.get(messageDoc).then(function (sfDoc) {
let upVote = sfDoc.data().upvotes + self.upvote;
transaction.update(messageDoc, { upvotes: upVote });
self.upvote = 0;
});
}).then(function() {
console.log("Transaction successfully committed!");
}).catch(function(err) {
console.log("Transaction failed: " + err);
});
}