/    Sign up×
Community /Pin to ProfileBookmark

Firebase RTDB – quizID only equals undefined in a certain place of script

I’m working on a website currently, and something strange is going on.

I have this code:
My code![My code](https://i.ibb.co/m8x8Xx6/script-problem.png)
CnP version:

“`javascript
var gameID = location.href.split(“&gameID=”)[1]

var quizID

firebase.database().ref(‘liveGames/’ + gameID).get().then((snapshot) => {
quizID = snapshot.val().quizID
})

console.log(“Quiz ID: ” + quizID)
“`

When I try to run that, the console logs `Quiz ID: undefined`.

But when I put it in a different spot as shown below,
Different spot![Different spot](https://i.ibb.co/N1XS1z8/script-problem-2.png)

The console says the quiz ID properly. (It says `Quiz ID: 7630579719`)

Also, if I put it in either spot, DevTools says the correct thing as well:
Correct DT 1![Correct DT 1](https://i.ibb.co/m9GBPjq/sp3.png)
Correct DT 2![Correct DT 2](https://i.ibb.co/NZrPjFn/sp4.png)

Why does this all happen, and how can I fix it to never say `undefined` and always say the right one?

Additional details:

  • I **do** have Firebase initialize app and credentials, etc.

  • I’m using Firebase version 8.4.3 (I find the modular v9 too hard to comprehend)
  • If you need any additional details, please ask in replies. Thanks a bunch!

    Bost

    to post a comment
    JavaScript

    7 Comments(s)

    Copy linkTweet thisAlerts:
    @BostauthorJan 07.2022 — I just noticed in the DevTools screenshots that the "0" (which is the player's score, by the way) is showing in different places in different screenshots. Does that change anything? Thanks again!
    Copy linkTweet thisAlerts:
    @SempervivumJan 07.2022 — Questions of this type are asked frequently. The reason is that your access to the database is working asynchronously, i. e. it takes a short moment until the result is ready. When placing the console.log after the call the result is not yet ready and quizID is undefined. In order to be sure that the result is ready you need to place all actions that require the result (quizID) inside the callback of the `then`.
    Copy linkTweet thisAlerts:
    @BostauthorJan 08.2022 — @Sempervivum#1641240 Thanks that helps my understanding a lot more. But I want the quizID to be globally accessible (by every script tag and out of the then statement.) I was thinking about making a function that waits until a variable (set by the then when it's triggered/activated) equals true or waits until quizID != undefined. Any ideas on how I could do that?
    Copy linkTweet thisAlerts:
    @SempervivumJan 08.2022 — Two options how to work around this situation come to my mind:

    1.
    > I was thinking about making a function that waits until a variable (set by the then when it's triggered/activated) equals true or waits until quizID != undefined

    Might be done by using setTimeout like so:
    ``<i>
    </i>function waitForIt() {
    if (quizID != undefined) {
    // Fine, the variable is available, do anything you like with it
    } else {
    // Variable is not yet available, wait a moment and try again:
    setTimeout(waitForIt, 100);
    }
    }
    waitForIt();<i>
    </i>
    `</CODE>
    However, again every processing based on the variable needs to be placed inside the function waitForIt.

    2.
    <QUOTE><i>&gt; </i>I want the quizID to be globally accessible (by every script tag and out of the then statement.)</QUOTE>
    <i>&gt; </i>
    You might consider loading these scripts not statically in the head section but dynamically in the callback of the database access:
    <CODE>
    `<i>
    </i>firebase.database().ref('liveGames/' + gameID).get().then((snapshot) =&gt; {
    quizID = snapshot.val().quizID;
    // Prepare HTML for including the script.
    scriptHtml = ...
    // Insert this HTML at the end of the head section:
    document.querySelector('head').insertAdjacentHTML('beforeend', scriptHtml);
    });<i>
    </i>
    ``
    Copy linkTweet thisAlerts:
    @rickmildonJan 14.2022 — I also have the same case... Did you solve this!
    Copy linkTweet thisAlerts:
    @BostauthorJan 19.2022 — @rickmildon#1641509 Indeed I did. It was due to me trying to access the undefined variable before it was set (it was right after the then callback.) The solution is to put all code that needs to access the variable inside of the then callback.
    Copy linkTweet thisAlerts:
    @rickmildonJan 20.2022 — A dedicated software development team https://mlsdev.com/blog/hire-app-developer can help you achieve more in a shorter period of time. You can hire a team that specializes in a particular area of technology. They are an extension of your own team. They should be treated as remote employees. In addition to developing software for you, they can also help you with other aspects of your business. A dedicated team can also provide you with IT services and support. Ultimately, a dedicated software development team can help you to reach your business goals.
    ×

    Success!

    Help @Bost spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.23,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...