Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase .on('value, function(){} ) executing twice with one push

I'm noticing something that I don't understand. I have the following "on" query setup in my code. When I 'push' a child to a lower level, it appears to me that the "on" callback function is getting raised twice.

fb.child('Question').on('value',function(ss){ console.log('on called'); });

Example Structure:

Question

----> Answers

----> {Answer 1} : { answer object }
----> {Answer 2} : { answer object }

I'm adding "answers" via the "push" function so the "key" for the answer is the uniquely created firebase "unique id".

fb.child('Question/Answers').push({the answer object});

At this point I'm only pushing new "answers", no update or set. What I'm seeing is that when I push a new "answer object", the "on" function is getting called twice.

I have double checked, and I don't have the "on" event handler attached more than once. I have also check to be sure the "push" is only getting called one time.

Is this the correct behavior? I'm "guessing" that the push is "inserting" the child and then "set"ing the answer object, which is causing the on to fire twice? But this doesn't sound right to me?

Obviously I'm fairly new to Firebase, so not sure if this is by design or not. But it make me nervous that big picture I'm running the "on" code more than once per single update?

like image 973
Dan Harris Avatar asked Feb 19 '15 20:02

Dan Harris


1 Answers

I had the same issue with firebase on 'value' event. It happens because of multiple listeners are attached for the same event, on page load or reauthentication etc.

The solution is to remove the existing listener before attaching new listener.

In firebase call off() event before on() event to fix this.

In this scenario,

fb.child('Question').off();
fb.child('Question').on('value',function(ss){ console.log('on called'); });

will fix the issue

like image 87
Mohammed Safeer Avatar answered Nov 11 '22 22:11

Mohammed Safeer