Get firebase.auth().currentUser with async/await

此生再无相见时 提交于 2019-12-07 13:23:36

问题


I successfully check user's authentication state with onAuthStateChange observer and redirect user to the Dashboard page (react-native project). However, on the dashboard I already want to show some user specific data, e.g. enrolled programs/statistics. For that I need currentUser object to be initialised and populated, which takes some time (I need uid from there to get some data from Database). Thus, i'm looking for some way to wait until this process finishes successfully. What I'm trying to do it to use async/await syntax in componentDidMount, but the result returned is null. (Same syntax successfully works in other screens, but fails in the first one)

async componentDidMount() {
  try {
    let uid = await firebase.auth().currentUser.uid;
    console.log(uid);
  } catch(error) {
    console.log(error);
  }
}

What could be the best way to wait for currentUser object being loaded using async/await syntax? I believe that the reason could be that firebase returns null as the first result and then correct uid as the second one.

For now for the workaround, I'm using simple setInterval function, but I do not want to increase amount of loading time that much.

  let waitForCurrentUser = setInterval(() => {
    if ( firebase.auth().currentUser.uid !== null ) {
        clearInterval(waitForCurrentUser);
        let uid = firebase.auth().currentUser.uid;
        this.setState({uid});
        return firebase.auth().currentUser.uid;
    } else {
      console.log('Wait for it');
    }
  }, 700);

回答1:


The equivalence of setInterval is : //calling the asynchronous function waitForCurrentUser(function(uid){ if(uid) console.log('the user id is',uid) })

   async waitForCurrentUser(userIdIs){

    try {
       let uid = await firebase.auth().currentUser.uid;
       if(uid)
       {
         clearInterval(waitForCurrentUser);        
         this.setState({uid});
         userIdIs(uid); 
       }
       else {
       console.log('Wait for it');
      }

    }

    catch(e){
     console.log(e)
    }

  //  return userIdIs(uid);//returns promise
  };

Cheers :)




回答2:


async getUid() {
        let user = await firebaseApp.auth().currentUser;
        let email = await user.uid;
}

Hope it's usefull for you



来源:https://stackoverflow.com/questions/43821921/get-firebase-auth-currentuser-with-async-await

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