Mayank Metha
Mayank Metha

Reputation: 172

Firebase JS Array losing scope

Firebase data is as follows

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

the code to retrieve election1, election2 is

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);
    }

Problem is electionArr is empty? How do i solve the issue

Upvotes: 0

Views: 35

Answers (2)

Himanshu
Himanshu

Reputation: 12685

Firebase function calls are asynchronous. Thats how it works you cannot assign an array from out of scope inside firebase on function call. Make your array available inside your once(value) function.

var conid;
var conRegex;
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) {
        var electionArr = [];
        snapshot.forEach(function(electionSnapshot) {
            conRegex = electionSnapshot.val().conRegex;
            if(conid.startsWith(conRegex)) {
                Object.keys(electionSnapshot.val()).map(k => {
                    electionArr.push(electionSnapshot.val()[k]);
                })
            }
        });
        console.log(electionArr);
    });
}

Upvotes: 2

Rosário P. Fernandes
Rosário P. Fernandes

Reputation: 11344

The once() function is asynchronous. You'll have to nest your reads and log your array to the console when all the data is read:

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);
            });
        }
    });
}

Upvotes: 1

Related Questions