Presence

With Presence, you can store a temporary string, boolean, number, or JSON object on a user. Use it to build mouse cursors, shared highlighting, draggable effects, or any other feature that doesn't require long-term persistence.

By design, presence has two rules:

  • A user can only write to their own keys, but can read from anyone else in the Room.
  • Presence keys expire.

Once you have a room setup, you can start using presence:

1const presence = room.presence()
2
3// This sets ONLY the current user's "position" key.
4presence.set("position", {
5 x: 20,
6 y: 30
7})

By default, presence keys expire in 1 minute unless updated. But you can set this timeout yourself, up to 3 days:

1const presence = room.presence()
2
3// Expires in 30 seconds
4presence.set("position", 30 * 1000, {
5 x: 20,
6 y: 30
7})

The presence set function returns an object containing the values for every user in the room. Each key of the object is a user id corresponding to the ones given in your Auth Webhook.

1const positions = presence.set("position", {
2 x: 20,
3 y: 30
4})
5
6positions["my-user-id"] // { x: 20, y: 30 }
7positions["some-user-id"] // { x: 40, y: 0 }
8

You can load the most up-to-date values with the getAll function:

1const positions = await presence.getAll("position")
2positions["my-user-id"] // { x: 20, y: 30 }

But most of the time, you can listen for incremental updates via the room:

1room.subscribe(presence, "position", positions => {
2 positions["some-user-id"]
3})

As a helper, you can also get exactly where this update is coming from:

1room.subscribe(presence, "position", (positions, from) => {
2 console.log(from) // "another-user-id"
3 positions["some-user-id"]
4})

By default, Presence keys expire when you leave the room.

Using Presence to see who's in the room

As the name implies, presence is the way you see who's in a room in Room Service. To accomplish this, just store a boolean value for the user.

1const presence = room.presence()
2
3// On load, set that this user is online
4presence.set("joined", true)
5
6// Then listen for other users to join
7room.subscribe(presence, "joined", whosJoined => {
8 whosJoined["some-user"] // true
9
10 Object.keys(whosJoined) // ["some-user", "another-user"]
11})
12
13
1const [joined, setJoined] = usePresence("myroom", "joined")
2
3useEffect(() => {
4 setJoined(true)
5}, [])