The useMessages hook provides access to message operations within a chat room, including sending, retrieving, updating, and deleting messages, as well as managing message reactions. When a listener is supplied, the hook automatically subscribes to new messages.
1
2
3
4
5
6
7
8
9
10
11
import { useMessages } from '@ably/chat/react';
const MyComponent = () => {
const { sendMessage, history } = useMessages({
listener: (event) => {
console.log('New message:', event.message.text);
},
});
return <button onClick={() => sendMessage({ text: 'Hello!' }).catch(console.error)}>Send</button>;
};This hook must be used within a ChatRoomProvider.
Parameters
The useMessages hook accepts an optional configuration object:
listeneroptionalMessageListenerreactionsListeneroptionalMessageReactionListenerrawReactionsListeneroptionalMessageRawReactionListenerReturns
The useMessages hook returns an object with the following properties:
sendMessagesendMessage()getMessagegetMessage()updateMessageupdateMessage()deleteMessagedeleteMessage()historyhistory()historyBeforeSubscribehistoryBeforeSubscribe()listener is provided.sendReactionsendReaction()deleteReactiondeleteReaction()roomStatusRoomStatusroomErrorErrorInfo or UndefinedconnectionStatusConnectionStatusconnectionErrorErrorInfo or UndefinedSend a message
sendMessage(params: SendMessageParams): Promise<Message>Send a message to the chat room. The message will be delivered to all subscribers in realtime.
This method uses the Ably Chat REST API and does not require the room to be attached.
Parameters
paramsrequiredSendMessageParamsReturns
Promise<Message>
Returns a promise. The promise is fulfilled with the sent Message object, or rejected with an ErrorInfo object.
Get a message
getMessage(serial: string): Promise<Message>Get a specific message by its unique serial identifier.
This method uses the Ably Chat REST API and does not require the room to be attached.
Parameters
serialrequiredStringReturns
Promise<Message>
Returns a promise. The promise is fulfilled with the Message object matching the given serial, or rejected with an ErrorInfo object.
Update a message
updateMessage(serial: string, params: UpdateMessageParams, details?: OperationDetails): Promise<Message>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 realtime.
This method uses the Ably Chat REST API and does not require the room to be attached.
Parameters
serialrequiredStringparamsrequiredUpdateMessageParamsdetailsoptionalOperationDetailsReturns
Promise<Message>
Returns a promise. The promise is fulfilled with the updated Message object, or rejected with an ErrorInfo object. The returned message will have its action property set to updated.
Delete a message
deleteMessage(serial: string, details?: OperationDetails): Promise<Message>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 realtime.
This method uses the Ably Chat REST API and does not require the room to be attached.
Parameters
serialrequiredStringdetailsoptionalOperationDetailsReturns
Promise<Message>
Returns a promise. The promise is fulfilled with the deleted Message object, or rejected with an ErrorInfo object. The returned message will have its action property set to deleted.
Get message history
history(params: HistoryParams): Promise<PaginatedResult<Message>>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.
This method uses the Ably Chat REST API and does not require the room to be attached.
Parameters
paramsrequiredHistoryParamsReturns
Promise<PaginatedResult<Message>>
Returns a promise. The promise is fulfilled with a PaginatedResult containing an array of Message objects, or rejected with an ErrorInfo object.
Get messages before subscription
historyBeforeSubscribe(params?: HistoryBeforeSubscribeParams): Promise<PaginatedResult<Message>>Get messages sent to the room up to the point at which the subscription was established. Only available when a listener is provided to the hook. Returns undefined if no listener was supplied.
Parameters
paramsoptionalHistoryBeforeSubscribeParamsReturns
Promise<PaginatedResult<Message>>
Returns a promise. The promise is fulfilled with a PaginatedResult containing an array of Message objects, or rejected with an ErrorInfo object.
Send a reaction
sendReaction(serial: string, params: SendMessageReactionParams): Promise<void>Sends a reaction to a specific chat message. The reaction is persisted and contributes to the message's reaction summary.
This method uses the Ably Chat REST API and does not require the room to be attached.
Parameters
serialrequiredStringparamsrequiredSendMessageReactionParamsReturns
Promise<void>
Returns a promise. The promise is fulfilled when the reaction has been sent, or rejected with an ErrorInfo object.
Delete a reaction
deleteReaction(serial: string, params?: DeleteMessageReactionParams): Promise<void>Removes a previously sent reaction from a chat message.
Parameters
serialrequiredStringparamsoptionalDeleteMessageReactionParamsReturns
Promise<void>
Returns a promise. The promise is fulfilled when the reaction has been deleted, or rejected with an ErrorInfo object.
Message
The Message interface represents a single message in a chat room.
serialStringclientIdStringuserClaimString or UndefinedtextStringtimestampDatemetadataMessageMetadataheadersMessageHeadersactionChatMessageActionversionMessageVersionreactionsMessageReactionSummaryPaginatedResult
A PaginatedResult represents a page of results from a paginated query such as history() or historyBeforeSubscribe().
itemsMessage[]Check for more pages
hasNext(): booleanReturns true if there are more pages available by calling next().
Check if last page
isLast(): booleanReturns true if this is the last page of results.
Get next page
next(): Promise<PaginatedResult<Message> | null>Returns a promise. The promise is fulfilled with the next page of results, or null if there are no more pages, or rejected with an ErrorInfo object.
Get first page
first(): Promise<PaginatedResult<Message>>Returns a promise. The promise is fulfilled with the first page of results, or rejected with an ErrorInfo object.
Get current page
current(): Promise<PaginatedResult<Message>>Returns a promise. The promise is fulfilled with the current page of results, or rejected with an ErrorInfo object.
Example
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { ChatMessageEventType, OrderBy, MessageReactionType } from '@ably/chat';
import { useMessages } from '@ably/chat/react';
import { useState, useCallback } from 'react';
function ChatMessages() {
const [messages, setMessages] = useState([]);
const { sendMessage, updateMessage, deleteMessage, history, sendReaction } = useMessages({
listener: (event) => {
setMessages((prev) => {
switch (event.type) {
case ChatMessageEventType.Created:
return [...prev, event.message];
case ChatMessageEventType.Updated:
case ChatMessageEventType.Deleted:
return prev.map((msg) =>
msg.serial === event.message.serial ? msg.with(event) : msg
);
default:
return prev;
}
});
},
reactionsListener: (event) => {
setMessages((prev) =>
prev.map((msg) =>
msg.serial === event.messageSerial
? msg.with(event)
: msg
)
);
},
});
const loadHistory = useCallback(async () => {
const result = await history({ limit: 50, orderBy: OrderBy.OldestFirst });
setMessages(result.items);
}, [history]);
const handleSend = useCallback(async (text) => {
await sendMessage({ text });
}, [sendMessage]);
const handleReact = useCallback(async (serial, emoji) => {
await sendReaction(serial, { name: emoji, type: MessageReactionType.Distinct });
}, [sendReaction]);
return (
<div>
<button onClick={loadHistory}>Load History</button>
{messages.map((msg) => (
<div key={msg.serial}>
<strong>{msg.clientId}</strong>: {msg.text}
<button onClick={() => handleReact(msg.serial, '👍')}>👍</button>
<button onClick={() => deleteMessage(msg.serial)}>Delete</button>
</div>
))}
<button onClick={() => handleSend('Hello!')}>Send</button>
</div>
);
}