I followed the tutorial pretty closely and am testing a "like" feature with a transaction. However, when I test it with 2 devices, the count doesn't seem to hold up well.
The error is when I click the like-button
on both devices, there are times that the counter goes up by two, but that are times that the counter goes up then down making it increase by 0 (when in fact there were two like buttons). Similar problem when there is two un-liking buttons pressed at the same time.
Unliking both buttons (at the same time) could also cause the counters to increase by two instead... when it should be decreasing it by two.
var liked; // global variable to check if button has been liked
document.getElementById("like-button").onclick = function () {
console.log("click");
database.ref("brands/" + brand + "/" + dealId).transaction(function(post) {
console.log("post:" , post);
if (post) {
if (post.likes && liked) {
post.likes--;
liked = false;
}
else {
post.likes++;
liked = true;
}
}
return post;
});
}
Wondering what is the problem here given I followed this transaction pretty closely. https://firebase.google.com/docs/database/web/read-and-write
Edit: JSON I have
Brand3
Brand3ID
impressions: 0
likes: 16
views: 0
Update: I noticed that the post
logs 3 times when i click the button simultaneously on 2 devices - which could possibly explain the failure in handling the global flag, but am still unable to resolve why. Usually post
should only log twice, one null and one when it detects the post
(Firebase realtime database transaction handler gets called twice most of the time)