The following code below attaches a watcher on the users/
path and logs the users when the value changes.
On firebase, this users/
tree is
When you attach a listeners to a node, the Firebase Database immediately evaluates whether the current connection has permission to read from that node. If it doesn't, it cancels the listener.
Since you start out unauthenticated, the listener is immediately cancelled. You can easily see this if you also pass an error callback into on()
:
firebase.database().ref('users').on('value', function(snapshot) {
console.log(snapshot.val())
}, function(error) {
console.error(error);
});
To solve this problem, you need to attach the listener after the user has been authenticated:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
firebase.database().ref('users').on('value', function(snapshot) {
console.log(snapshot.val())
}, function(error) {
console.error(error);
});
} else {
// No user is signed in.
... do other stuff
}
});