Plattsy Plattsy - 4 months ago 21
Javascript Question

Why does firebase "on" "value" not run the listener function when the reference doesn't exist, but "once" "value" does?

Say I'm listening to a widget:

const ref = firebase.database().ref(`widgets/${widgetId}`);
ref.on('value', function(snapshot){
console.log(snapshot.val()); // <-- I never see this if ref doesn't exist!
}


If that widget doesn't exist I want to know about it. I'd expect
snapshot.val()
to return
null
. But the problem is the function isn't run at all. So I can't event check for
null
. It just stays silent.

The weird thing is, this fixes it:

const ref = firebase.database().ref(`widgets/${widgetId}`);
ref.once('value', function(){});
ref.on('value', function(snapshot){
console.log(snapshot.val()); // <-- Now is null!
}


Now the function provided to
on
is run with
snapshot.val()
===
null
. Is this a bug or am I doing something wrong?

Answer

I needed to upgrade Firebase to the lastest version (3.0.5 -> 3.2.0)

npm install --save firebase