I am currently working on enhancing the online functionality of my chat app by implementing a presence system using Firebase Realtime Database. Here is the code snippet that I have created for this purpose:
db refers to Firestore and dbt refers to the Realtime Database
import { auth, db, dbt } from "@/firebase/firebase";
import { ref as rtdbRef, set, onValue, onDisconnect } from "firebase/database";
const connectedRef = rtdbRef(dbt, ".info/connected");
const myConnectionsRef = rtdbRef(dbt, `status/` + user.uid);
onValue(connectedRef, (snap) => {
if (snap.val() === false) {
return ;
}
onDisconnect(myConnectionsRef).set("disconnected").then(() => {
updateFirestoreUser(true, user);
set(myConnectionsRef, "connected")
});
In order to achieve my goal of updating the 'isOnline' variable in Firestore cloud when a user goes offline, I came across a solution from the Firebase documentation. However, I encountered errors with each line of the provided code:
var userStatusFirestoreRef = firebase.firestore().doc('/status/' + uid);
var isOfflineForFirestore = {
state: 'offline',
last_changed: firebase.firestore.FieldValue.serverTimestamp(),
};
var isOnlineForFirestore = {
state: 'online',
last_changed: firebase.firestore.FieldValue.serverTimestamp(),
};
firebase.database().ref('.info/connected').on('value', function(snapshot) {
if (snapshot.val() == false) {
userStatusFirestoreRef.set(isOfflineForFirestore);
return;
};
userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function() {
userStatusDatabaseRef.set(isOnlineForDatabase);
userStatusFirestoreRef.set(isOnlineForFirestore);
})
});