Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve data in Firebase exactly once

I have a real time database with firebase and i'm using the following code to connect to the database and get some data from it.

window.onload = function(){
var databaseWebsites = firebase.database().ref('/websites').orderByChild('votes');
console.log(databaseWebsites);
databaseWebsites.on('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {

      var webTemp = document.getElementById(childSnapshot.val().id);
      webTemp.style.order = order;
      var webText = webTemp.getElementsByClassName('likeText');
      webText[0].innerHTML = childSnapshot.val().votes;
      order--;
  });

  order = 0;
});

It gets all the data, in order and uses it correctly.

The problem is, I don't want the data on the front end to update until the user refreshes the page. The system is a voting system that is ordered by votes value, if it was constantly updating it would be a bad user experience.

Any help will be appreciated.

Thanks

like image 610
Joe Cory Avatar asked Sep 23 '16 15:09

Joe Cory


2 Answers

Change the on to once, Firebase on listens for changes in your database node and sends a response.

databaseWebsites.on('value', function(snapshot) {

to

databaseWebsites.once('value', function(snapshot) {

An excerpt from Firebase doc

The value event is called every time data is changed at the specified database reference, including changes to children. To limit the size of your snapshots, attach only at the lowest level needed for watching changes.

Visit this url to read more

like image 163
Fowotade Babajide Avatar answered Oct 11 '22 13:10

Fowotade Babajide


The accepted response is not correct (maybe outdated?) because once() requires to add a then()

It's actually

databaseWebsites.once('value').then(function(snapshot) {}

that replaces

databaseWebsites.on('value', function(snapshot) {}
like image 39
stallingOne Avatar answered Oct 11 '22 15:10

stallingOne