Reputation: 528
So when i'm closing my browser i would like to add
const timestamp = Date.now();
const username = "MyUser";
const message = "I have logged out";
db.ref("messages/222222222222222" + timestamp).set({
username,
message,
});
I have tried:
const presenceRef = firebase.database().ref("disconnectmessage");
presenceRef.onDisconnect().set("I disconnected!");
But i can't add my code in to it:
db.ref("messages/222222222222222" + timestamp).set({
username,
message,
});
How can i add my own event listener to onDisconnect?
This not working for me for some reason:
var connectedRef = firebase.database().ref(".info/connected");
connectedRef.on("value", (snap) => {
if (snap.val() === true) {
console.log("connected");
} else {
//My code here is not working
// When i'm closing the broswer it doesn't add it to
// messages
}
});
Upvotes: 0
Views: 48
Reputation: 599661
You should be able to just do this:
db.ref("messages/222222222222222" + timestamp).onDisconnect().set({
username,
message,
});
Your last snippet will not work, because by the time the .info/connected
gets set to false, the connection to the server has been lost already so you can't write to the remote database anymore
Upvotes: 1