Optionaloptions: UseChatConnectionOptionsOptional configuration for the hook
A UseChatConnectionResponse containing the current connection status and error
An Ably.ErrorInfo When used outside of a ChatClientProvider
import * as Ably from 'ably';
import React from 'react';
import { ChatClient, ConnectionStatus } from '@ably/chat';
import { ChatClientProvider, useChatConnection } from '@ably/chat/react';
// Component that displays connection status
const ConnectionStatus = () => {
const { currentStatus, error } = useChatConnection({
onStatusChange: (change) => {
console.log(`Connection changed from ${change.previous} to ${change.current}`);
if (change.error) {
console.error('Connection error:', change.error);
}
}
});
return (
<div>
<div>
Status: {currentStatus}
</div>
{error && (
<div>
Error: {error.message} (Code: {error.code})
</div>
)}
</div>
);
};
const chatClient: ChatClient; // existing ChatClient instance
// App component with provider setup
const App = () => {
return (
<ChatClientProvider client={chatClient}>
<ConnectionStatus />
</ChatClientProvider>
);
};
export default App;
React hook that provides the current connection status and error between the client and Ably, and allows the user to listen to connection status changes overtime.
The hook will automatically clean up listeners when the component unmounts and update the connection state whenever the underlying chat client changes.
Note: This hook must be used within a ChatClientProvider component tree.