The usePresenceListener hook provides live presence information for all users in a room. It automatically subscribes to presence events and maintains an up-to-date roster of presence members. Use usePresence to manage the current user's own presence state.
React
1
2
3
4
5
6
7
8
9
10
11
12
13
import { usePresenceListener } from '@ably/chat/react';
const MyComponent = () => {
const { presenceData } = usePresenceListener();
return (
<ul>
{presenceData.map((member) => (
<li key={member.clientId}>{member.clientId}</li>
))}
</ul>
);
};This hook must be used within a ChatRoomProvider.
Parameters
The usePresenceListener hook accepts an optional configuration object:
listeneroptionalPresenceListenerA callback invoked whenever the presence state changes. Removed when the component unmounts.
A callback to detect and respond to discontinuities.
A callback invoked when the room status changes. Removed when the component unmounts.
A callback invoked when the connection status changes. Removed when the component unmounts.
Returns
The usePresenceListener hook returns an object with the following properties:
presenceDataPresenceMember[]The current state of all presence members, updated in realtime. Only emitted while presence is not syncing.
errorErrorInfo or UndefinedTracks presence listener errors during asynchronous data fetching. Set when the initial presence data fetch fails or when errors occur after presence events. Clears upon successful new presence event processing.
roomStatusRoomStatusThe current status of the room, kept up to date by the hook.
roomErrorErrorInfo or UndefinedAn error object if the room is in an errored state.
connectionStatusConnectionStatusThe current connection status, kept up to date by the hook.
connectionErrorErrorInfo or UndefinedAn error object if there is a connection error.
Example
React
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
36
37
38
import { PresenceEventType } from '@ably/chat';
import { usePresenceListener } from '@ably/chat/react';
function OnlineUsers() {
const { presenceData, error } = usePresenceListener({
listener: (event) => {
switch (event.type) {
case PresenceEventType.Enter:
console.log(`${event.member.clientId} joined`);
break;
case PresenceEventType.Leave:
console.log(`${event.member.clientId} left`);
break;
case PresenceEventType.Update:
console.log(`${event.member.clientId} updated their status`);
break;
}
},
});
if (error) {
return <p>Error loading presence: {error.message}</p>;
}
return (
<div>
<h3>Online ({presenceData.length})</h3>
<ul>
{presenceData.map((member) => (
<li key={member.clientId}>
{member.clientId}
{member.data?.status && ` (${member.data.status})`}
</li>
))}
</ul>
</div>
);
}