Firebase 3 - ref.getAuth() equivalent

北城以北 提交于 2020-07-02 18:32:08

问题


In Firebase 2 I was able to do a synchronous check to see if the user was logged in, e.g:

if (!ref.getAuth()) ..go to login page
else ..show page

I can access the currentUser state with firebase.auth().currentUser so I tried to do:

if (!firebase.auth().currentUser) ..go to login page
else ..show page

The problem is that this is always initially null, so it redirects to the login page, then a few moments later onAuthStateChanged happens and the user is logged in.

Is there still a way to synchronously check this? Or otherwise is there a promise I can listen to so that I can show a loading spinner or something? Thanks.


回答1:


I've been using an auth state listener to determine if the user is signed in.

  auth.onAuthStateChanged(function(user) {
    console.log('authStateChanged', user);
    if (user) {
      console.log("Welcome UID:" + user.uid);
    }
  });

When you attach that listener right away, it will fire with the correct state.

When I run the app, sign in and reload the page, the log outputs:

authStateChanged Fl {...}

Welcome UID:052289713245805425655890E9024AB4ADBA5404B3C0

So you can use the first time the listener is called to detect if the user is already signed in.




回答2:


I had the same issue, and because I'm using Angular, I found a synchronous call $getAuth() in AngularFire. https://github.com/firebase/angularfire/blob/master/docs/reference.md#getauth

Maybe there's an equivalent in ReactFire library as well. :)



来源:https://stackoverflow.com/questions/37367640/firebase-3-ref-getauth-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!