-
Notifications
You must be signed in to change notification settings - Fork 253
/
Copy pathrtdb_sample_presence_app.js
35 lines (28 loc) · 1.37 KB
/
rtdb_sample_presence_app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// This snippet file was generated by processing the source file:
// ./database-next/offline.js
//
// To update the snippets in this file, edit the source and then run
// 'npm run snippets'.
// [START rtdb_sample_presence_app_modular]
import { getDatabase, ref, onValue, push, onDisconnect, set, serverTimestamp } from "firebase/database";
// Since I can connect from multiple devices or browser tabs, we store each connection instance separately
// any time that connectionsRef's value is null (i.e. has no children) I am offline
const db = getDatabase();
const myConnectionsRef = ref(db, 'users/joe/connections');
// stores the timestamp of my last disconnect (the last time I was seen online)
const lastOnlineRef = ref(db, 'users/joe/lastOnline');
const connectedRef = ref(db, '.info/connected');
onValue(connectedRef, (snap) => {
if (snap.val() === true) {
// We're connected (or reconnected)! Do anything here that should happen only if online (or on reconnect)
const con = push(myConnectionsRef);
// When I disconnect, remove this device
onDisconnect(con).remove();
// Add this device to my connections list
// this value could contain info about the device or a timestamp too
set(con, true);
// When I disconnect, update the last time I was seen online
onDisconnect(lastOnlineRef).set(serverTimestamp());
}
});
// [END rtdb_sample_presence_app_modular]