Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firebase.initializeApp callback/promise?

This is my web page

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Calcolo Diliuzioni</title>

    </head>
    <body>

        <h1>My app</h1>

        <!-- Libreria per gestire l'autenticazione con google -->
        <script src="https://apis.google.com/js/platform.js" async defer></script>

        <!-- Firebae config -->
        <script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
        <script>
        // Initialize Firebase
        var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        storageBucket: "",
        };
        firebase.initializeApp(config);
        </script>

        <script type="text/javascript">
            var user = firebase.auth().currentUser;
            if (user) {
                console.log(user);
            } else {
                console.log(user);
            }
        </script>
    </body>
</html>

Let's assume I have an already logged user. When I load the page in the console I got null. While I'm expecting to have the current user's object.

If I run the same code in the browser console

var user = firebase.auth().currentUser;
if (user) {
    console.log(user);
} else {
    console.log(user);
}

I'm able to get the current user's object.

I think that the firebase.initializeApp(config); has some async behavior. What's the right way to work around it? Should I use a promise or something on the firebase.initializeApp(config); function? A sort of callback..

like image 880
gaggina Avatar asked May 30 '16 13:05

gaggina


2 Answers

initialize app is synchronous. However, determining the current user state is asynchronous. The right way to determine the current auth state is to use an observer: https://firebase.google.com/docs/auth/web/manage-users

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in and currentUser will no longer return null.
  } else {
    // No user is signed in.
  }
});
like image 80
bojeil Avatar answered Sep 21 '22 14:09

bojeil


I would combine two methods together:

function canActivate(){
    return new Promise(resolve => {
        if (firebase.auth().currentUser) {
            resolve(true);
        } else {
            const unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
                unsubscribe();
                if (user) {
                    resolve(true);
                } else {
                    resolve(false);
                }
            });
        }
    });
}

At SPA, if user already login and user can go to any pages get firebase.auth().currentUser == true. But if user reload page, get firebase.auth().currentUser == false. User need to wait firebase.initializeApp(config); finished, so add firebase.auth().onAuthStateChanged to wait init finished.

like image 39
foxiris Avatar answered Sep 22 '22 14:09

foxiris