JavaScript global variable remains unaffected by scope change

Currently stuck in my JavaScript file, attempting to upload data but encountering a perplexing issue. It seems that myUid variable isn't updating as expected. Can anyone provide guidance on how to address this issue and shed some light on why myUid is failing to update?

var myUid = '33';

firebase.auth().signInAnonymously().catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
  });

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var isAnonymous = user.isAnonymous;
        window.myUid = user.uid;
        // ...
    } else {
        // User is signed out.
        // ...
    }
    // ...
});


function writeUserData() {
    database.ref('users/').set({
    profileID: myUid,
  });
};

writeUserData();

Warm regards, Sam

Answer №1

myUid value is only updated once the callback for onAuthStateChanged is processed asynchronously. When you call the writeUserData() function in your main execution flow, the mentioned callback may still be in progress.

A more effective approach would be to eliminate the global variable and invoke the writeUserData function from within the onAuthStateChanged callback, passing the user uid as an argument.

function writeUserData(userUid) {
    database.ref('users/').set({
    profileID: userUid,
  });
};

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var isAnonymous = user.isAnonymous;
        writeUserData(user.uid);
        // ...
    } else {
        // User is signed out.
        // ...
    }
    // ...
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular.js: automatically select default option based on ID

In my angular.js single page application, I am retrieving initial data from a rest endpoint. The data consists of a list of IDs representing saved models and a tree of options for cascading dropdowns. How can I automatically set the default path in the t ...

Use Javascript to create commands and variables specific to the domain or site of a webpage

Currently, I have implemented the code below to fetch the latest tweet. However, I am looking for a way to customize the TWITTERUSERNAME based on the domain where the template is being used. This template is shared across multiple domains. <script type ...

When Simple Git is tested individually, it functions properly. However, when incorporated into a larger Node.js project, it fails to work

I've encountered an issue with a simple JavaScript Git code that seems to be acting sporadically. While it occasionally pushes random commits, most of the time it fails to work as intended. Take a look at the code snippet below: const jsonfile = requi ...

Transferring streaming data from Node.js to an ElasticSearch database

Currently, my Node.js script is extracting data from a large USPTO Patent XML file (approximately 100mb) to create a patentGrant object. This object includes details such as publication number, country, date, and type of patent. I am working on storing a ...

Extracting input value using HTML and JavaScript

Is there a way to utilize the content of a form field within a confirmation dialog box that pops up upon submission, as illustrated below? <form action='removefinish.php' method='post' accept-charset='UTF-8'> Role: < ...

Troubleshooting: Page Unable to Import/Execute Linked JavaScript on WebStorm with Node.js Backend

I've been following W3School's jQuery tutorial, but I'm encountering some issues with importing scripts to an HTML document hosted on a Node server in WebStorm. I have properly installed and enabled the jQuery libraries under Preferences &g ...

What impact does setting a variable equal to itself within a Dom Object have?

Within my code example, I encountered an issue with image sources and hrefs in a HTML String named tinymceToHTML. When downloading this html String, the paths were set incorrectly. The original image sources appeared as "/file/:id" in the String. However, ...

How do I go about updating my code for welcome messages from discord.js v12 to v13?

While watching a YouTube tutorial on welcome messages, I decided to copy the entire code. However, when I tried using this code with discord.js v13, it didn't work. Strangely enough, everything seemed to function perfectly fine with discord.js v12. In ...

Implementing React and Material UI - Customizing Navigation Buttons/Links according to Routes

The following code snippet represents the main entry point of a React app, app.js, which includes the router endpoints. Below the app.js code, you will find the code for a Nav component, which serves as the navigation menu. I am looking to structure this ...

The PopupControlExtender in ajaxToolkit seems to be malfunctioning when used with a textbox that has Tinymce

I recently built a website using ASP.NET, and I have a feature where a small tooltip appears on the right side of a text box when the user focuses on it. To achieve this, I am using the ajaxToolkit:PopupControlExtender in my code. <asp:TextBox ...

The Node function will yield a BluebirdJS Promise

I've encountered a minor issue with this script. While it functions properly, the "runTenant" method is not returning a promise that needs to be resolved with "all()". Here's the code snippet in question: Promise.resolve(runTenant(latest)).then ...

Omitting the "undefined" values from an array enclosed within square brackets

Here is the array that I am working with. I am currently trying to remove the undefined value in row 2 of the array before tackling the duplicate square brackets issue. Despite attempting various methods, I am struggling to eliminate the undefined value - ...

Sending parameters within ajax success function

To streamline the code, I started by initializing the variables for the selectors outside and then creating a function to use them. Everything was working fine with the uninitialized selector, but as soon as I switched to using the variables, it stopped wo ...

What causes the datepicker to flicker in React when an input field is in focus?

Can someone explain why the datepicker is flickering in React when focusing on the input field? I have integrated the following date picker in my demonstration: https://www.npmjs.com/package/semantic-ui-calendar-react However, it is flickering on focus, ...

Validating multiple fields that are added dynamically using jQuery

I am facing an issue with form validation using jQuery. The problem is that when one field is valid, the form gets submitted automatically. Here is a link to my code: http://jsfiddle.net/cvL0ymu7/. How can I ensure that all fields are validated before subm ...

Guide to developing a personalized useReducer with integrated decision-making and event activation

I am interested in creating a custom hook called useTextProcessor(initialText, props). This hook is designed for managing and manipulating text (string) within a React state. It utilizes useReducer to maintain a cumulative state. Here is the implementation ...

How can we use jQuery to extract an HTML element's external stylesheet and add it to its "style" attribute?

My goal is to extract all CSS references from an external stylesheet, such as <link rel="stylesheet" href="css/General.css">, and add them to the existing styling of each HTML element on my page (converting all CSS to inline). The reason for this re ...

The message "Missing property 'type' in type 'typeof WithXXX'" indicates an error

Currently, I am working on a project using React in combination with Typescript. My goal is to create a higher order component based on the react-dnd library. The problem arises within the DragSource section of the react-dnd component. Here is the relevant ...

Breaking down strings using delimiters in JavaScript

Looking for a solution to parse a string with markers: 'This is {startMarker} the string {endMarker} for {startMarker} example. {endMarker}' I want to transform it into an array that looks like this: [ {marker: false, value: 'This is&ap ...

Employing jQuery to add div elements, with each div possessing a distinct identifier

Hey, I'm working on using jQuery to dynamically generate cards with unique IDs and random numbers. I believe there must be a better way to achieve this. Could you help me with two things? First, how can I continuously add random numbers to the cards? ...