Refs not rerunning after onAuthStateChanged changes Firebase 3.0.0

前端 未结 1 1736
臣服心动
臣服心动 2021-01-07 10:02

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

相关标签:
1条回答
  • 2021-01-07 10:35

    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
      }
    });
    
    0 讨论(0)
提交回复
热议问题