Kanishka
Kanishka

Reputation: 1137

Firebase ref.on("value" is getting called even without a change in value - node.js

I am trying to observe a change in my firebase DB.

This is my structure

DB - Authenticate : true

I am listening to changes in Authenticate like this in my node.js app

var authRef = firebase.database().ref('Authentication');
      authRef.on('value', function(snapshot) {
              console.log(snapshot.val());
              res.send(snapshot.val());
      });

But as soon as I call authRef.on , it is fetching the previous value instead of waiting for a change.

Please advice.

Upvotes: 0

Views: 1870

Answers (1)

Ziya ERKOC
Ziya ERKOC

Reputation: 839

It is the nature of firebase listeners.
When you create a value listener it will fetch the data at least once.
I would do the following to prevent this:

var i = 0
var authRef = firebase.database().ref('Authentication');
  authRef.on('value', function(snapshot) {

          if( i != 0){
            console.log(snapshot.val());
            res.send(snapshot.val());
          }
          i++
  });

It will not consider the first call if you do so

Upvotes: 4

Related Questions