attach a callback to onauthStateChanged listener firebaseHow can I pass a parameter to a setTimeout() callback?How to access the correct `this` inside a callback?Firebase stop listening onAuthStateChangedMaking an Observable from a callbackFirebase WEB - Email Verification not being sent. What's wrong with the codeHow to get current user ID in Firebase Cloud Functions with Firestore trigger?Initialize documentReference through string failsHow to get the uid of the authenticated Firebase user in a Cloud Functions storage triggerFirestore rules Path not workingFetching UID from Firebase from username

Are there reliable, formulaic ways to form chords on the guitar?

Check disk usage of files returned with spaces

Does git delete empty folders?

From France west coast to Portugal via ship?

Can I submit a paper computer science conference using an alias if using my real name can cause legal trouble in my original country

Why should care be taken while closing a capacitive circuit?

Just one file echoed from an array of files

Polar contour plot in Mathematica?

Control GPIO pins from C

Did they show Truman doing private things (toilet, etc) when filming him for 24 hours, 7 days a week?

Installing the original OS X version onto a Mac?

Would it be illegal for Facebook to actively promote a political agenda?

Starships without computers?

How best to join tables, which have different lengths on the same column values which exist in both tables?

Sinc interpolation in spatial domain

Atmospheric methane to carbon

Installing certbot - error - "nothing provides pyparsing"

Number of matrices with bounded products of rows and columns

Best model for precedence constraints within scheduling problem

Can I check a small array of bools in one go?

Uploaded homemade mp3 to icloud music library, now "not available in my country or region"

Are unaudited server logs admissible in a court of law?

Reducing contention in thread-safe LruCache

!I!n!s!e!r!t! !b!e!t!w!e!e!n!



attach a callback to onauthStateChanged listener firebase


How can I pass a parameter to a setTimeout() callback?How to access the correct `this` inside a callback?Firebase stop listening onAuthStateChangedMaking an Observable from a callbackFirebase WEB - Email Verification not being sent. What's wrong with the codeHow to get current user ID in Firebase Cloud Functions with Firestore trigger?Initialize documentReference through string failsHow to get the uid of the authenticated Firebase user in a Cloud Functions storage triggerFirestore rules Path not workingFetching UID from Firebase from username






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















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










share|improve this question
































    2















    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










    share|improve this question




























      2












      2








      2








      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










      share|improve this question
















      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







      javascript firebase firebase-authentication






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 28 at 7:01







      Taio

















      asked Mar 27 at 13:51









      TaioTaio

      4288 silver badges22 bronze badges




      4288 silver badges22 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          1














          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.






          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55378884%2fattach-a-callback-to-onauthstatechanged-listener-firebase%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            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.






            share|improve this answer





























              1














              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.






              share|improve this answer



























                1












                1








                1







                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.






                share|improve this answer













                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 27 at 15:43









                Doug StevensonDoug Stevenson

                105k12 gold badges121 silver badges147 bronze badges




                105k12 gold badges121 silver badges147 bronze badges





















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid …


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55378884%2fattach-a-callback-to-onauthstatechanged-listener-firebase%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

                    Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?