How to check if anything in firebase reference exists in javascript

Viewed 137

So I have some code for my firebase project, and it checks when something is changed but it still runs the function even when nothing is in there and i dont want it... check below and please help!!!

   <script>
     firebase.database().ref('Bolos/').on('value', function(snapshot) { 
      M.toast({html: '<i class="material-icons">check_circle</i><span>Current Bolos Or Just Updated!'})
     });
   </script>

Basically What i wanna do is this : When something is added, updated or deleted:

  • Run That M.Toast

when reference is empty:

  • Do Nothing
2 Answers

If you want to check if the Bolos node exists, that'd be:

firebase.database().ref('Bolos/').on('value', function(snapshot) { 
  if (snapshot.exists()) {
    M.toast({html: '<i class="material-icons">check_circle</i><span>Current Bolos Or Just Updated!'})
  }
});

If you want to detect whether a child node was added, modified or deleted, you'll want to use the relevant child_ events:

function showToast() {
  M.toast({html: '<i class="material-icons">check_circle</i><span>Current Bolos Or Just Updated!'})
}

firebase.database().ref('Bolos/').on('child_added', showToast);
firebase.database().ref('Bolos/').on('child_removed', showToast);
firebase.database().ref('Bolos/').on('child_changed', showToast);

As per the firebase docs on() method read and listen to the path if anything changes.
Point to note here is that on() method first return the snapshot first time when the listener is attached and after that whenever any data including child changes.

The event callback is passed a snapshot containing all data at that location, including child data. If there is no data, the snapshot will return false when you call exists() and null when you call val() on it.
So you can add if condition to check is snapshot exists, then execute your code else do nothing.

Reference - https://firebase.google.com/docs/database/web/read-and-write#listen_for_value_events

Related