@ably/chat - v1.1.1
    Preparing search index...

    Interface UseMessagesResponse

    The response from the useMessages hook.

    interface UseMessagesResponse {
        connectionError?: ErrorInfo;
        connectionStatus: ConnectionStatus;
        deleteMessage: (
            serial: string,
            details?: OperationDetails,
        ) => Promise<Message>;
        deleteReaction: (
            serial: string,
            params?: DeleteMessageReactionParams,
        ) => Promise<void>;
        getMessage: (serial: string) => Promise<Message>;
        history: (params: HistoryParams) => Promise<PaginatedResult<Message>>;
        historyBeforeSubscribe?: (
            params: Omit<HistoryParams, "orderBy">,
        ) => Promise<PaginatedResult<Message>>;
        roomError?: ErrorInfo;
        roomStatus: RoomStatus;
        sendMessage: (params: SendMessageParams) => Promise<Message>;
        sendReaction: (
            serial: string,
            params: SendMessageReactionParams,
        ) => Promise<void>;
        updateMessage: (
            serial: string,
            updateParams: UpdateMessageParams,
            details?: OperationDetails,
        ) => Promise<Message>;
    }

    Hierarchy (View Summary)

    Index

    Properties

    connectionError?: ErrorInfo

    If there's a connection error it will be available here.

    connectionStatus: ConnectionStatus

    Provides the connection status of the Ably connection.

    deleteMessage: (serial: string, details?: OperationDetails) => Promise<Message>

    A 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:

    • The returned Message instance represents the state after deletion. If you have active subscriptions, use the event payloads from those subscriptions instead of the returned instance for consistency.
    • 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.

    Type Declaration

      • (serial: string, details?: OperationDetails): Promise<Message>
      • Parameters

        • serial: string

          The unique identifier of the message to delete

        • Optionaldetails: OperationDetails

          Optional details to record about the delete action

        Returns Promise<Message>

        A Promise that resolves to the deleted Message object with isDeleted set to true and deletion metadata populated, or rejects with:

        • Ably.ErrorInfo when the message is not found, user lacks permissions, or network/server errors occur
    const { deleteMessage } = useMessages();

    const handleDeleteMessage = async (serial: string) => {
    try {
    await deleteMessage(serial, {
    description: 'User deleted message'
    });
    } catch (error) {
    console.error('Failed to delete message:', error);
    }
    };
    deleteReaction: (
        serial: string,
        params?: DeleteMessageReactionParams,
    ) => Promise<void>

    A shortcut to the MessageReactions.delete method.

    Deletes a previously sent reaction from a chat message.

    The deletion behavior depends on the reaction type:

    • Unique: Removes the client's single reaction (name not required)
    • Distinct: Removes a specific reaction by name
    • Multiple: Removes all instances of a reaction by name

    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.

    Type Declaration

      • (serial: string, params?: DeleteMessageReactionParams): Promise<void>
      • Parameters

        • serial: string

          The unique identifier of the message to remove the reaction from

        • Optionalparams: DeleteMessageReactionParams

          Optional parameters specifying which reaction to delete

        Returns Promise<void>

        A Promise that resolves when the reaction has been deleted, or rejects with Ably.ErrorInfo

    const { deleteReaction } = useMessages();

    const handleDeleteReaction = async (messageSerial: string, emoji: string) => {
    try {
    await deleteReaction(messageSerial, {
    name: emoji
    });
    } catch (error) {
    console.error('Failed to delete reaction:', error);
    }
    };
    getMessage: (serial: string) => Promise<Message>

    A 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.

    Type Declaration

      • (serial: string): Promise<Message>
      • Parameters

        • serial: string

          The unique serial identifier of the message to retrieve

        Returns Promise<Message>

        A Promise that resolves to the Message object, or rejects with:

        • Ably.ErrorInfo when the message is not found or network/server errors occur
    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);
    }
    };
    history: (params: HistoryParams) => Promise<PaginatedResult<Message>>

    A 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.

    Type Declaration

    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);
    }
    };
    historyBeforeSubscribe?: (
        params: Omit<HistoryParams, "orderBy">,
    ) => Promise<PaginatedResult<Message>>

    Retrieves 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.

    Type Declaration

      • (params: Omit<HistoryParams, "orderBy">): Promise<PaginatedResult<Message>>
      • 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:

        • If the client experiences a discontinuity event (i.e. the connection was lost and could not be resumed), the starting point of historyBeforeSubscribe will be reset.
        • Calls to historyBeforeSubscribe will then wait for continuity to be restored before resolving.
        • Once continuity is restored, the subscription point will be set to the beginning of this new period of continuity. To ensure that no messages are missed (or updates/deletes), you should call historyBeforeSubscribe after any period of discontinuity to re-populate your local state.

        Parameters

        • params: Omit<HistoryParams, "orderBy">

          Parameters for the history query.

        Returns Promise<PaginatedResult<Message>>

        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();
    roomError?: ErrorInfo

    If there's an error with the room it will be available here.

    roomStatus: RoomStatus

    Provides the status of the room.

    sendMessage: (params: SendMessageParams) => Promise<Message>

    A 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.

    Type Declaration

      • (params: SendMessageParams): Promise<Message>
      • Parameters

        • params: SendMessageParams

          Message parameters containing the text and optional metadata/headers

        Returns Promise<Message>

        A Promise that resolves to the sent Message object, or rejects with:

        • Ably.ErrorInfo when the message fails to send due to network issues, authentication problems, or rate limiting
    const { sendMessage } = useMessages();

    const handleSendMessage = async () => {
    try {
    await sendMessage({
    text: 'Hello world!',
    });
    } catch (error) {
    console.error('Failed to send message:', error);
    }
    };
    sendReaction: (
        serial: string,
        params: SendMessageReactionParams,
    ) => Promise<void>

    A shortcut to the MessageReactions.send method.

    Sends a reaction to a specific chat message.

    Note:

    • The behavior depends on the reaction type configured for the room.
    • 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.

    Type Declaration

      • (serial: string, params: SendMessageReactionParams): Promise<void>
      • Parameters

        • serial: string

          The unique identifier of the message to react to

        • params: SendMessageReactionParams

          The reaction parameters including the reaction name

        Returns Promise<void>

        A Promise that resolves when the reaction has been sent, or rejects with Ably.ErrorInfo

    const { sendReaction } = useMessages();

    const handleSendReaction = async (messageSerial: string, emoji: string) => {
    try {
    await sendReaction(messageSerial, {
    name: emoji
    });
    } catch (error) {
    console.error('Failed to send reaction:', error);
    }
    };
    updateMessage: (
        serial: string,
        updateParams: UpdateMessageParams,
        details?: OperationDetails,
    ) => Promise<Message>

    A 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 method uses PUT-like semantics. If metadata or headers are omitted from updateParams, they will be replaced with empty objects, not merged with existing values.
    • The returned Message instance represents the state after the update. If you have active subscriptions, use the event payloads from those subscriptions instead of the returned instance for consistency.
    • 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.

    Type Declaration

      • (
            serial: string,
            updateParams: UpdateMessageParams,
            details?: OperationDetails,
        ): Promise<Message>
      • Parameters

        • serial: string

          The unique identifier of the message to update

        • updateParams: UpdateMessageParams

          The new message content and properties

        • Optionaldetails: OperationDetails

          Optional details to record about the update action

        Returns Promise<Message>

        A Promise that resolves to the updated Message object with isUpdated set to true and update metadata populated, or rejects with:

        • Ably.ErrorInfo when the message is not found, user lacks permissions, or network/server errors occur
    const { updateMessage } = useMessages();

    const handleUpdateMessage = async (serial: string, newText: string) => {
    try {
    await updateMessage(serial, {
    text: newText
    }, {
    description: 'User edited message'
    });
    } catch (error) {
    console.error('Failed to update message:', error);
    }
    };