Taio
Taio

Reputation: 3734

attach a callback to onauthStateChanged listener firebase

I have this code which I need to just return a uid so that I can later use the Id to carry out firestore operations

$(document).ready(function () {
    var uid;
    auth.onAuthStateChanged(function (user) {
        if (user != null) {
            uid = user.uid; 
            console.log(typeof uid)//returns a string ;
        }
    });

    console.log(uid);
    function fetch() {
        var docRef = db.collection("Users").doc(uid);
        docRef.get().then(function (doc) {
            console.log(doc.data);
        }).catch(function (error) {
            console.log("Error getting document:", error);
        });
    }
});

How can I store the uid to later retrieve it for database operations. Currently, running the check function returns an error that uid is undefined. Same if I try to log the uid to console. I am guessing the function is run before the listener resolves but how would i work around this. Setting a timer would also not help due to different internet connection speeds between users

(addition of code)

check1();
check3();
//fetch();

function check1() {
    if (typeof uid === 'undefined') {
        console.log("not ready");
        return false
    }
}

function check3() {
    if (check1 == false) {
        check1();
    } else {
        console.log("ready");  //here this logs ready
        console.log(typeof uid); //then here it logs "undefined" still
        fetch(); //so this function call brings the error
    }
}

function fetch() {
    var docRef = db.collection("Users").doc(uid);
    docRef.get().then(function (doc) {
        console.log(doc.data();
    }).catch(function (error) {
        console.log("Error getting document:", error);
    });
}

why is the check3 function logging ready if uid is undefined. I also need a particular link to be hidden until the uid has a value. How can I improve the above code leave hiding the link

Upvotes: 2

Views: 97

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317487

Your guess is almost certainly correct that you're calling check before the authentication completes successfully. Setting a timer won't really help this becomes bulletproof.

Since we don't know when or under what conditions you need to call check, it's difficult to recommend a different course of action. At the very least, check should check if uid is not defined yet, and refuse to do anything if it's not there.

Typically, UIs will be coded not to let the user do anything until they've successfully logged in.

Upvotes: 1

Related Questions