Home > OS >  Detaching user data snapshot listeners on web app
Detaching user data snapshot listeners on web app

Time:11-30

I have a snapshot listener that listen for real time changes on user data I'm storing with Firestore. The listener is there due to a chat feature I am developing because I need to update the list of chat Id's that the user has in realtime in case a new chat was added. The problem is with detaching the listener when the user is disconnected or has lost connection. Any suggestions on how I could achieve this without using the onDisconnect method from Real Time DB since I can't call the detachListner() method with that.

Example:

here is my user doc

{
    name:"Brad"
    avatar:"https://avatar.com"
    chats: [
        {
            id: 1.,
            member_name:"John",
            avatar:""
        },
        {
            id: 2.,
            member_name:"John",
            avatar:""
        },
     ]
}

I have an active snapshot listener on this doc,

let unsubscribeListener;

export const getChatSnapshot = (user_id, callback) => {
  unsubscribeChatListener = onSnapshot(
    doc(db, "users", user_id),
    (doc) => {
      callback(doc.data());
    },
    (error) => {
      console.log(error.message);
    }
  );
};

is there a way disconnect the listener when user disconnect or close the page. since with onDisconnect I only have set, delete ...

Is there a way to have something like this.

onDisconnect(userStatusDatabaseRef)
// call unsubscribeListener when user is disconnected.
// like unsubscribeListener()
      .set(isOfflineForDatabase)
      .then(() => {
        set(userStatusDatabaseRef, isOnlineForDatabase);
      });

CodePudding user response:

If you're asking whether you can perform a write to Firestore after the user disconnections, similar to Realtime Database's onDisconnect handlers, the answer is unfortunately no.

Firestore uses a different protocol than Realtime Database, and that protocol doesn't allow for detecting the first connection or disconnecting. If you need those features within Firebase, Realtime Database is your only option.

Keep in mind that you can use both Firestore and Realtime Database in the same application. In fact, there's a solution guide that explains how to build a presence system on Firestore using Realtime Database and Cloud Functions behind the scenes.

  • Related