The scope of a JS array is being lost in Firebase

The Firebase data structure looks like this:

-users
--demo1
---conid:1
-election
--election1
---conRegex:1
--election2
---conRegex:1

Here is the code to retrieve election1 and election2:

var conid;
    var conRegex;
    var electionArr = [];
    if(uidAnonymous != null) {
        db.ref('users/'+user).once('value', function(snapshot) {
            if(snapshot.exists()) {
                conid = snapshot.val().conid;
            }
        });
        db.ref('election/').once('value', function(snapshot) {
            snapshot.forEach(function(electionSnapshot) {
                conRegex = electionSnapshot.val().conRegex;
                if(conid.startsWith(conRegex)) {
                    electionArr.push(electionSnapshot.key.toString());
                }
            });
        });
        console.log(electionArr);
    }

Currently, the issue is that electionArr is empty. How can I resolve this problem?

Answer №1

It is important to remember that Firebase function calls operate asynchronously. This means that you cannot assign an array from a different scope inside the 'on' function call in Firebase. To ensure your array is accessible, it should be declared and manipulated within the 'once(value)' function.

var connectionId;
var conRegex;
if(idUser != null) {
    db.ref('users/'+user).once('value', function(snapshot) {
        if(snapshot.exists()) {
            connectionId = snapshot.val().connectionId;
        }
    });
    db.ref('election/').once('value', function(snapshot) {
        var electionArray = [];
        snapshot.forEach(function(electionSnapshot) {
            conRegex = electionSnapshot.val().conRegex;
            if(connectionId.startsWith(conRegex)) {
                Object.keys(electionSnapshot.val()).map(key => {
                    electionArray.push(electionSnapshot.val()[key]);
                })
            }
        });
        console.log(electionArray);
    });
}

Answer №2

The function known as once() operates asynchronously, as explained in detail in this insightful article. To ensure all the data is read before logging your array to the console, it's important to nest your reads:

var conid;
var conRegex;
var electionArr = [];
if(uidAnonymous != null) {
    db.ref('users/'+user).once('value', function(snapshot) {
        if(snapshot.exists()) {
            conid = snapshot.val().conid;

            db.ref('election/').once('value', function(snapshot) {
                snapshot.forEach(function(electionSnapshot) {
                    conRegex = electionSnapshot.val().conRegex;
                    if(conid.startsWith(conRegex)) {
                        electionArr.push(electionSnapshot.key.toString());
                    }
                });
                console.log(electionArr);
            });
        }
    });
}

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

Is Angular automatically assigned to `window.angular` on a global level when it is loaded as a CommonJS module?

When I import Angular 1.4 in my Webpack build entry point module as a CommonJS module using var angular = require("angular");, it somehow ends up being accessible in the global namespace of the browser (as window.angular). Upon examining the source code o ...

Having trouble rendering the response text from the API fetched in Next.js on a webpage

I've written some code to back up a session border controller (SBC) and it seems to be working well based on the output from console.log. The issue I'm facing is that the response comes in as a text/ini file object and I'm unable to display ...

Jasmine spies call through problem detected

I can't seem to get my code to work properly and I keep encountering this error: TypeError: undefined is not an object (evaluating 'GitUser.GetGitUser('test').then') ... Check out the code snippets below: app.controller(&apo ...

The NodeJS nedb function seems to be ignoring the await keyword

The time it takes for the function checkExists to run is too lengthy. Despite attempting to implement await and async functions, using var exists = await checkExists(data.email); still results in undefined value due to not properly awaiting for checkExists ...

Customize and adjust the default color for dark themes in Material-UI

When using Material-UI and switching to a dark theme, you may notice that some components change their color to #424242 while others change to #212121. This color inconsistency stems from the use of theme.palette.grey: theme.palette.grey[800]: '#424 ...

Utilize useEffect to dynamically populate several dropdown menus with data

I am currently implementing a method to populate two dropdowns in my component using useEffects. function fetch_data_for_dropdown1() { return axios.get("http://127.0.0.1:5001/dropdownonedata"); } function fetch_data_for_dropdown2() { return axios ...

"During the testing phase, the req.body object is found

I'm currently performing unit testing on my express application using Mocha and Chai. However, when I attempt to use req.body in the test file to parse the object, I only receive undefined in the testing results. In my server (app.js), I have alread ...

Providing data in response to a completed form submission

As a beginner, I'm attempting to accomplish the following task: a user selects options from three dropdown menus within a form, and the chosen values are then sent to another file for processing. action="process.php" method="post" In the processing ...

Protractor is unable to locate the password input field on Gmail using its ID

Currently, I am in the process of configuring Protractor to test my application. However, I am encountering a roadblock as it requires authentication through Gmail and I am struggling with the login process: describe('Vivace Home page', function ...

Dispatch in React Redux is not intercepted

I've been grappling with this issue for hours and still can't seem to find a solution. When I click the button, the function "getLocation" is being triggered (Confirmed it) However, the dispatch is not getting passed to the reducer. After r ...

VueJS - repeating input fields for file uploads

I need help removing duplicate items from an array in JavaScript, but when I try to delete one, it always deletes the last occurrence! let app = new Vue({ el: '#app', data: { items: [] }, methods: { addItem() { this.items ...

using app.use to directly pass arguments without delay (NODE.JS)

I'm currently figuring out why the code 1 is functioning properly, while the code 2 is not... app.js: // Implementing Routes var server = require('./routes/server'); app.use('/', server); Route.js: var express = require(&a ...

Dealing with asynchronous tasks in JavaScript

I am currently delving into the world of Node development and struggling to grasp the asynchronous nature of JavaScript and Node.js. My project involves creating a microservices backend web server using Express in the gateway service, which then translates ...

Understanding the functionality of imports within modules imported into Angular

I have been scouring through the documentation trying to understand the functionality of the import statement in JavaScript, specifically within the Angular framework. While I grasp the basic concept that it imports modules from other files containing expo ...

Looping through nested arrays in an array of objects with Angular's ng-repeat

I'm struggling to access an array within an array of objects in my AngularJS project. Here's the HTML: <li ng-repeat="ai in main.a2"> <div np-repeat="bi in ai.b"> <span ng-bind="bi"></span>b2 </div> </l ...

I am experiencing difficulties with my data not reaching the function in my component.ts file within Angular

My current project involves integrating Google Firebase to handle the login functionality. I encountered an issue where the data inputted from the HTML page to the component.ts file was not being processed or reaching Firebase. However, when I initialized ...

The Vue.js input for checkboxes and radios fails to toggle when both :checked and @input or @click are used simultaneously

Check out this example on JSFiddle! <script src="https://unpkg.com/vue"></script> <div id="app"> <label> <input type="checkbox" name="demo" :checked="isChecked" @input=" ...

What is the best approach to comparing two times in JavaScript to ensure accuracy after an NTP time update?

We are facing an issue with a JavaScript function that retrieves the start and end times of two events: var startTime = new Date().getTime(); // A lengthy task is executed var endTime = new Date().getTime(); The problem we encountered is that getTime() s ...

Using React to pass a value through state when handling changes

Trying to implement handleChange and handleSubmit methods for a login page in React. Set username and password values in state, update them when form inputs change, then submit using the updated values. However, values print as undefined in the console. N ...

The issue arises when the d3 startAngle and endAngle values are set to NaN, resulting in an

I am working with a dataset that includes the following information: { current: 5 expected: 8 gap: -3 id: 3924 name: "Forhandlingsevne" progress: "0" type: 2 } Now, I have implemented the ...