useMessages

Open in

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.

React

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:

listeneroptionalMessageListener
A callback invoked when chat message events occur.
reactionsListeneroptionalMessageReactionListener
A callback invoked when reaction summaries change for messages in the room.
rawReactionsListeneroptionalMessageRawReactionListener
A callback invoked for individual reaction events on messages in the room.
onDiscontinuityoptionalDiscontinuityListener
A callback to detect and respond to discontinuities in the message stream.
onRoomStatusChangeoptionalRoomStatusChange
A callback invoked when the room status changes. Removed when the component unmounts.
onConnectionStatusChangeoptionalConnectionStatusChange
A callback invoked when the connection status changes. Removed when the component unmounts.

Returns

The useMessages hook returns an object with the following properties:

sendMessagesendMessage()
Sends a message to the chat room.
getMessagegetMessage()
Retrieves a single message by its serial.
updateMessageupdateMessage()
Updates a message's content.
deleteMessagedeleteMessage()
Soft-deletes a message.
historyhistory()
Retrieves historical messages with pagination.
historyBeforeSubscribehistoryBeforeSubscribe()
Retrieves messages sent before the subscription was established. Only available when a listener is provided.
sendReactionsendReaction()
Sends a reaction to a message.
deleteReactiondeleteReaction()
Removes a reaction from a message.
roomStatusRoomStatus
The current status of the room, kept up to date by the hook.
roomErrorErrorInfo or Undefined
An error object if the room is in an errored state.
connectionStatusConnectionStatus
The current connection status, kept up to date by the hook.
connectionErrorErrorInfo or Undefined
An error object if there is a connection error.

Send 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

paramsrequiredSendMessageParams
Message parameters containing the text and optional metadata/headers.

Returns

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

serialrequiredString
The unique serial identifier of the message to retrieve.

Returns

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

serialrequiredString
The unique identifier of the message to update.
paramsrequiredUpdateMessageParams
The new message content and properties.
detailsoptionalOperationDetails
Details to record about the update action.

Returns

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

serialrequiredString
The unique identifier of the message to delete.
detailsoptionalOperationDetails
Details to record about the delete action.

Returns

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

paramsrequiredHistoryParams
Query parameters to filter and control message retrieval.

Returns

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

paramsoptionalHistoryBeforeSubscribeParams
Query parameters to filter message retrieval. Messages are returned in order of most recent to oldest.

Returns

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

serialrequiredString
The serial of the message to react to.
paramsrequiredSendMessageReactionParams
The reaction parameters.

Returns

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

serialrequiredString
The serial of the message to remove the reaction from.
paramsoptionalDeleteMessageReactionParams
Parameters identifying which reaction to delete.

Returns

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.

serialString
The unique identifier of the message.
clientIdString
The client ID of the user who created the message.
userClaimString or Undefined
The user claim attached to this message by the server. Only present if the publishing user's JWT contained a claim for the room in which this message was published.
textString
The text content of the message.
timestampDate
The timestamp at which the message was created.
metadataMessageMetadata
Extra information attached to the message for features like animations or linking to external resources. Always set; empty object if no metadata was provided.
headersMessageHeaders
Additional information in Ably realtime message extras, usable for features like livestream timestamping or message flagging. Always set; empty object if none provided.
actionChatMessageAction
The action type indicating if the message was created, updated, or deleted.
versionMessageVersion
Information about the current version of this message.
reactionsMessageReactionSummary
The reactions summary for this message.

PaginatedResult

A PaginatedResult represents a page of results from a paginated query such as history() or historyBeforeSubscribe().

itemsMessage[]
The current page of results.

Check for more pages

hasNext(): boolean

Returns true if there are more pages available by calling next().

Check if last page

isLast(): boolean

Returns 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

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

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>
  );
}