Firebase's SET method isn't working

Viewed 382

I'm using firebase and I wrote a simple function in Javascript to SET and UPDATE data.

function setLastOnline(userID, InOut){
    var dbLastonline = firebase.database().ref().child("lastonline");
    if (InOut) {
        dbLastonline.child(userID).set({
            "isConnected":true,
            "connectedby":"web",
            "lastIn":firebase.database.ServerValue.TIMESTAMP,
            "lastOut":0
        });
    } else {
        dbLastonline.child(userID).update({
            "isConnected":false,
            "connectedby":"web",
            "lastOut":firebase.database.ServerValue.TIMESTAMP
        });
    }
}

When I call the function to perform the SET method, nothing happens... No data in database and no error code...

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            setLastOnline(user.uid, true);
        }
      }

But when I call the same function to perform the UPDATE, everything works fine.

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            setLastOnline(user.uid, false);
            firebase.auth().signOut();
        }`
     }`

What am I doing wrong?

Thanks in advance.

2 Answers

Since there is no actual solution given, I thought it would be worth sharing the solution that I was able to piece together. The solution I pieced together was to use .then to force .set() to run completely before it moves onto loading the next screen. as shown below.

firebase.database().ref().child('/churches/' + userName ).set(data).then( function(){     
    window.location = "Homepage.html";
});

Since I'm new to programming I don't know how to implement this method into the author's code, however, I believe the code above is what the original code trying to achieve. If you want to find out how .then works you can look up "promises in javascript".

Related