Firebase SET method not working
I am using firebase and I wrote a simple function in Javascript for 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 execute the SET method, nothing happens ... No data in the database and no error code ...
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
setLastOnline(user.uid, true);
}
}
But when I call the same function to do 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.
source to share
I found a bug. The above function is correct and works well. The problem was that I called window.open () shortly after calling setLastOnline (). Like this:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
setLastOnline(user.uid, true);
window.open('another_page.php','_self');
}
}
So Firebase execution stops and VERBOSE in Chrome console ( [Violation] Avoid using document.write () on line 362 www.gstatic.com/firebasejs/3.6.8/firebase.js ).
Hello!
source to share
Since no actual solution is given, I thought it was worth sharing the solution I was able to put together. The solution I put together was to use .then to get .set () to work completely before it moves on to load the next screen. as shown below.
firebase.database().ref().child('/churches/' + userName ).set(data).then( function(){
window.location = "Homepage.html";
});
Since I am new to programming, I do not know how to implement this method in the authoring code, however, I believe that the above code is what the original code was trying to achieve. If you want to know how .then works, take a look at "promises in javascript".
source to share