Vadim T
Vadim T

Reputation: 528

Javascript Firebase real time database onDisconnect

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

Answers (1)

Frank van Puffelen
Frank van Puffelen

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

Related Questions