Optional ReadonlyconnectionIf there's a connection error it will be available here.
ReadonlyconnectionProvides the connection status of the Ably connection.
ReadonlydeleteA shortcut to the Messages.delete method.
Delete a message in the chat room.
This method performs a "soft delete" on a message, marking it as deleted rather than permanently removing it. The deleted message will still be visible in message history but will be flagged as deleted. Subscribers will receive a deletion event in real-time.
Important: The Promise may resolve before OR after the deletion event is received from the realtime channel. Subscribers may see the deletion event before this method completes.
Note:
This is a stable reference and will not be changed between renders for the same room.
The unique identifier of the message to delete
Optionaldetails: OperationDetailsOptional details to record about the delete action
A Promise that resolves to the deleted Message object with
isDeleted set to true and deletion metadata populated, or rejects with:
ReadonlydeleteA shortcut to the MessageReactions.delete method.
Deletes a previously sent reaction from a chat message.
The deletion behavior depends on the reaction type:
Note: This method uses the Ably Chat REST API and so does not require the room to be attached to be called.
This is a stable reference and will not be changed between renders for the same room.
The unique identifier of the message to remove the reaction from
Optionalparams: DeleteMessageReactionParamsOptional parameters specifying which reaction to delete
A Promise that resolves when the reaction has been deleted, or rejects with Ably.ErrorInfo
ReadonlygetA shortcut to the Messages.get method.
Get a specific message by its unique serial identifier.
This method retrieves a single message using its serial, which is a unique identifier assigned to each message when it's created.
NOTE: This method uses the Ably Chat REST API and so does not require the room to be attached to be called.
This is a stable reference and will not be changed between renders for the same room.
The unique serial identifier of the message to retrieve
A Promise that resolves to the Message object, or rejects with:
const { getMessage } = useMessages();
const handleGetMessage = async (messageSerial: string) => {
try {
const message = await getMessage(messageSerial);
console.log('Retrieved message:', message.text);
console.log('From:', message.clientId);
} catch (error) {
console.error('Failed to get message:', error);
}
};
ReadonlyhistoryA shortcut to the Messages.history method.
Get messages that have been previously sent to the chat room.
This method retrieves historical messages based on the provided query options, allowing you to paginate through message history, filter by time ranges, and control the order of results.
NOTE: This method uses the Ably Chat REST API and so does not require the room to be attached to be called.
This is a stable reference and will not be changed between renders for the same room.
Query parameters to filter and control the message retrieval
A Promise that resolves to a PaginatedResult containing an array of Message objects and methods for pagination control, or rejects with ErrorCode.InvalidArgument when the query fails due to invalid parameters
const { history } = useMessages();
const loadHistory = async () => {
try {
const result = await history({
limit: 50,
orderBy: OrderBy.NewestFirst
});
console.log('Previous messages:', result.items);
// Paginate through additional pages if available
if (result.hasNext()) {
const nextPage = await result.next();
console.log('Next page:', nextPage?.items);
}
} catch (error) {
console.error('Failed to load history:', error);
}
};
Optional ReadonlyhistoryRetrieves the previous messages in the room.
This method is available only if a MessageListener has been provided in the UseMessagesParams. Calling will return a promise that resolves to a paginated response of the previous messages received in the room, up until the listener was attached, in newest-to-oldest order.
It is advised to call this method after any discontinuity event; to retrieve messages that may have been missed before the listener was re-attached.
See the MessageSubscriptionResponse.historyBeforeSubscribe documentation for more details.
This is removed when the component unmounts or when the previously provided listener is removed.
Get the previous messages that were sent to the room before the listener was subscribed. This can be used to populate a room on initial subscription or to refresh local state after a discontinuity event.
NOTE:
historyBeforeSubscribe will be reset.historyBeforeSubscribe will then wait for continuity to be restored before resolving.historyBeforeSubscribe after any period of discontinuity to
re-populate your local state.Parameters for the history query.
A promise that resolves with the paginated result of messages, in newest-to-oldest order.
import * as Ably from 'ably';
import { ChatClient, ChatMessageEventType } from '@ably/chat';
const chatClient: ChatClient; // existing ChatClient instance
const room = await chatClient.rooms.get('general-chat');
// Local message state
let localMessages: Message[] = [];
const updateLocalMessageState = (messages: Message[], message:Message): void => {
// Find existing message in local state
const existingIndex = messages.findIndex(m => m.serial === message.serial);
if (existingIndex === -1) {
// New message, add to local state
messages.push(message);
} else {
// Existing message, update local state
messages[existingIndex] = messages[existingIndex].with(message);
}
// Messages should be ordered by serial
messages.sort((a, b) => a.serial < b.serial ? -1 : (b.serial < a.serial ? 1 : 0));
};
// Subscribe a listener to message events
const subscription = room.messages.subscribe((event) => {
console.log(`Message ${event.type}:`, event.message.text);
updateLocalMessageState(localMessages, event.message);
});
// Attach to the room to start receiving message events
await room.attach();
// Get historical messages before subscription
try {
const history = await subscription.historyBeforeSubscribe({ limit: 50 });
console.log(`Retrieved ${history.items.length} historical messages`);
// Process historical messages
history.items.forEach(message => {
console.log(`Historical: ${message.text} from ${message.clientId}`);
updateLocalMessageState(localMessages, message);
});
} catch (error) {
console.error('Failed to retrieve message history:', error);
}
// Subscribe a listener to message events as before
const { historyBeforeSubscribe } = // subscribed listener response
// Subscribe to discontinuity events on the room
room.onDiscontinuity(async (reason) => {
console.warn('Discontinuity detected:', reason);
// Clear local state and re-fetch messages
localMessages = []
try {
// Fetch messages before the new subscription point
const history = await subscription.historyBeforeSubscribe({ limit: 100 });
// Merge each message into local state
history.items.forEach(message => {
updateLocalMessageState(localMessages, message);
});
console.log(`Refreshed local state with ${localMessages.length} messages`);
} catch (error) {
console.error('Failed to refresh messages after discontinuity:', error);
}
});
// Attach to the room to start receiving events
await room.attach();
Optional ReadonlyroomIf there's an error with the room it will be available here.
ReadonlyroomProvides the status of the room.
ReadonlysendA shortcut to the Messages.send method.
Send a message to the chat room using the Ably Chat API.
Important: The Promise may resolve before OR after the message is received from the realtime channel. This means subscribers may see the message before the send operation completes.
NOTE: This method uses the Ably Chat REST API and so does not require the room to be attached to be called.
This is a stable reference and will not be changed between renders for the same room.
Message parameters containing the text and optional metadata/headers
A Promise that resolves to the sent Message object, or rejects with:
ReadonlysendA shortcut to the MessageReactions.send method.
Sends a reaction to a specific chat message.
Note:
This is a stable reference and will not be changed between renders for the same room.
The unique identifier of the message to react to
The reaction parameters including the reaction name
A Promise that resolves when the reaction has been sent, or rejects with Ably.ErrorInfo
ReadonlyupdateA shortcut to the Messages.update method.
Update a message in the chat room.
This method modifies an existing message's content, metadata, or headers. The update creates a new version of the message while preserving the original serial identifier. Subscribers will receive an update event in real-time.
Important: The Promise may resolve before OR after the update event is received from the realtime channel. Subscribers may see the update event before this method completes.
Note:
This is a stable reference and will not be changed between renders for the same room.
The unique identifier of the message to update
The new message content and properties
Optionaldetails: OperationDetailsOptional details to record about the update action
A Promise that resolves to the updated Message object with
isUpdated set to true and update metadata populated, or rejects with:
The response from the useMessages hook.