The useChatConnection hook provides the current connection status and error state between the client and Ably. It supports listener callbacks for status changes and automatically cleans up listeners on component unmount.
React
1
2
3
4
5
6
import { useChatConnection } from '@ably/chat/react';
const MyComponent = () => {
const { currentStatus, error } = useChatConnection();
return <p>Connection: {currentStatus}</p>;
};This hook must be used within a ChatClientProvider.
Parameters
The useChatConnection hook accepts an optional configuration object:
A callback invoked whenever the connection status changes. The listener is removed when the component unmounts.
Returns
The useChatConnection hook returns an object with the following properties:
currentStatusConnectionStatusThe current status of the connection, kept up to date by the hook.
errorErrorInfo or UndefinedAn error that provides a reason why the connection has entered the new status, if applicable. Kept up to date by the hook.
ConnectionStatus
The status of the connection to Ably.
InitializedA temporary state for when the library is first initialized. The value is
initialized.ConnectingThe library is currently connecting to Ably. The value is
connecting.ConnectedA connection exists and is active. The value is
connected.DisconnectedThe library is currently disconnected from Ably, but will attempt to reconnect. The value is
disconnected.SuspendedThe library is in an extended state of disconnection, but will attempt to reconnect. The value is
suspended.FailedThe library is currently disconnected from Ably and will not attempt to reconnect. The value is
failed.ClosingAn explicit request by the developer to close the connection has been sent to the Ably service. The value is
closing.ClosedThe connection has been explicitly closed by the client. No reconnection attempts are made automatically. The value is
closed.ConnectionStatusChange
Describes a change in connection status.
currentConnectionStatusThe new connection status.
previousConnectionStatusThe previous connection status.
errorErrorInfo or UndefinedAn error that provides a reason why the connection has entered the new status, if applicable.
retryInNumber or UndefinedThe time in milliseconds that the client will wait before attempting to reconnect, if applicable.
Example
React
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { ConnectionStatus } from '@ably/chat';
import { useChatConnection } from '@ably/chat/react';
function ConnectionIndicator() {
const { currentStatus, error } = useChatConnection({
onStatusChange: (change) => {
console.log('Status changed from', change.previous, 'to', change.current);
if (change.retryIn) {
console.log('Retrying in', change.retryIn, 'ms');
}
},
});
return (
<div>
<span className={currentStatus === ConnectionStatus.Connected ? 'online' : 'offline'}>
{currentStatus}
</span>
{error && <p>Error: {error.message}</p>}
</div>
);
}