Transferring the value of a variable from Block to Global Scope in FIRESTORE

I'm currently working on an App in Firebase, utilizing FireStore as my primary Database.

Below is a snippet of code where I define a variable order and set it to a value of 1.

Afterwards, I update the value to 4 and use console.log to verify. Everything checks out fine.

However, after running the function and logging the variable again, it reverts back to 1 instead of retaining the updated value.

This is My code (Please pay attention to the //comments)

    console.log("Initial Value : " + order); // logs 'Initial Value : 1'

    //A function that retrieves another value from FireStore Database and assigns it to the variable.
    function getField() {
      db.collection("index")
        .doc("artNum")
        .get()
        .then(function(doc) {
          order = doc.data().artNum; //Reassigning the variable to '4' here.
          console.log("Value assigned : " + order); // logs 'Value assigned : 4'
        })
        .catch(err => {
          console.log(err);
        });
    }

    getField(); 
    console.log("Updated Value : " + order); // logs " Updated Value : 1 " when it should be 4

I would greatly appreciate any assistance in identifying what's causing this discrepancy in my code or if there's something crucial missing.

Answer №1

To create a global variable named order, you can simply use window.order = yourValue (if in a browser environment, replace window with global if in Node.js).

It's important to note that the code is asynchronous, meaning that updates occur after the getField function is called. Therefore, trying to retrieve the new value immediately will not work as expected. However, the getFields function returns a Promise that will always be resolved due to the catch clause.

Here is an example of how this should work:

console.log("Value initialized: " + order); // outputs 'Value initialized: 1'

// This function fetches another value from the Firestore Database and assigns it to the global variable.
function getField() {
  return db.collection("index")
    .doc("artNum")
    .get()
    .then(function(doc) {
      order = doc.data().artNum; // Variable reassigned to '4' here.
      console.log("Value assigned: " + order); // outputs 'Value assigned: 4'
    })
    .catch(err => {
      console.log(err);
    });
}

// Calling the getField function and logging the updated value when it resolves.
getField().then(() => console.log("Updated value:", order)); 

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

Revealing and concealing adjacent elements within a specified class

In an attempt to create a carousel that functions by hiding and showing images when the next and previous buttons are clicked, I have organized my images in a table and assigned the li elements a class of 'li'. There are four images in total, wit ...

Implementing React router for dynamic page rendering

I'm struggling to make sense of a particular piece of code. Can someone provide an explanation? I'm particularly confused about the role of "props" in this section and how it is essential for the code to work correctly. If I remove "props," my co ...

Track and manage date ranges inclusive of specific times

http://jsfiddle.net/7vzapm49/1/ var startdatearr = [new Date("04 Dec 2014 14:30:00").toUTCString(), new Date("07 Dec 2014 14:30:00").toUTCString()]; var enddatearr = [new Date("05 Dec 2014 14:30:00").toUTCString(), new Date("08 Dec 2014 14:30:00").toUTCSt ...

Fetching JSON data using Promise.all results in an empty response

I'm facing an issue in my code where I am trying to fetch data from two different JSON files and then return them as arrays. Even after implementing the solution below, it doesn't seem to be working as expected. Can someone guide me on how I can ...

API requests seem to be failing on the server side, yet they are functioning properly when made through the browser

My current project involves utilizing an API that provides detailed information about countries. I've set up an express server to handle requests to this API, but for some reason it's not making the request. Interestingly, when I directly access ...

Is it possible to adjust the color of this AnchorLink as I scroll down?

Currently struggling to update the color of a logo as I scroll. While the navigation bar successfully changes colors, the logo remains stagnant. Here is the excerpt from my existing code: navigation.js return ( <Nav {...this.props} scrolled={this ...

JQuery automatically selects an action upon 'change' event, but does not do so upon 'select' event

I'm hoping my explanation was clear. I have a text input field that utilizes the jQuery UI autoselect function. When a user selects an option, the input field auto-fills correctly. However, I encounter an issue when a user types something but does not ...

Site performance stalls when a trailing slash is present in the URL while using Express routing

Whenever I visit a page on my development site with a URL like localhost:8000/news, everything loads perfectly fine. However, if I add a trailing slash to the URL, such as localhost:8000/news/, the entire site freezes. It seems to be trying to load partial ...

Sending dynamic data through AJAX to a CodeIgniter controller is a common task that allows for seamless

Can anyone help me with retrieving data from a looping form in CodeIgniter? The form works fine, but I'm struggling to fetch the looping data in the controller. Here's my view (form): <form action="#" id="ap_data"> <div class="table-r ...

Anticipating the resolution of one promise before tackling the next in Angular.js

Is it possible in Angular.js to ensure that a given promise is resolved before another dependent promise? Consider the following code snippet: User.getAllUsers().then(function(users) { $scope.users = users; for (var i = 0; i < users.length; i+ ...

The initial $http POST in Angular ends up hitting the error path within the .then function despite the successful execution of the

Something strange is happening to me. This peculiar behavior occurs only on the initial POST request. However, when I resubmit the form, the subsequent requests work perfectly fine. The first $http post call leads to the error function in .then, even thou ...

Is there a method similar to insertBefore that works with arrays and/or HTMLCollections?

Is there a vanilla JavaScript or jQuery function that works like Node.insertBefore(), but for arrays and/or HTMLCollections? An example of what I'm looking for: var list = document.getElementsByClassName("stuff"); var nodeToMove = list[0]; var other ...

Steps for making a toggle button with Bootstrap

Initially, I developed a web application using HTML, CSS, and JavaScript. Later on, I was requested to recreate it using Bootstrap as well. While I managed to complete the task successfully, I encountered an issue where toggle buttons in the web app revert ...

Modifying worldwide variables within an ajax request

After spending considerable time attempting to achieve the desired outcome, I am faced with a challenge. My goal is to append the object from the initial ajax call after the second ajax call. However, it appears that the for loop is altering the value to ...

Is there a way for me to determine which specific dependency is triggering a warning due to utilizing another dependency?

After analyzing my browser console, I found the following warnings: index.js:126 [WDS] Warnings while compiling. warnings @ index.js:126 (anonymous) @ socket.js:47 sock.onmessage @ SockJSClient.js:67 EventTarget.dispatchEvent @ sockjs.js:170 ...

Double the Power of jQuery Live Search with Two Implementations on a Single Website

I recently implemented a JQuery Live Search feature that is working perfectly. Here is the JQuery script: <script type="text/javascript"> $(document).ready(function(){ $('.search-box input[type="text"]').on("keyup input", function(){ ...

Data sent as FormData will be received as arrays separated by commas

When constructing form data, I compile arrays and use POST to send it. Here's the code snippet: let fd = new FormData(); for (section in this.data.choices) { let key = section+(this.data.choices[section] instanceof Array ? '[]' : '& ...

Preventing Javascript array elements from being overwritten: Best practices

My challenge lies with the addToClients() function, which is designed to add a new value to the clients array whenever a button is pressed. The issue I am facing is that each time I press submit, the previous element in the array gets replaced by the new o ...

Is it possible to set the input form to be read-only?

I need to create a "read-only" version of all my forms which contain multiple <input type="text"> fields. Instead of recoding each field individually, I'm looking for a more efficient solution. A suggestion was made to use the following: <xs ...

Learn how to display each element in a list one by one with a three-second interval and animated transitions in React

Let's consider a scenario where we have a component called List: import React, { Component } from 'react'; class List extends Component { constructor() { super(); this.state = { list: [1, 2, 3, 5] } ...