useDeliveries

The useDeliveries hook calls a handler for every delivery on the transport's channel while the component is mounted. A delivery holds the decoded event and the Ably message it came from, in the same shape as subscribe(). The hook reads the latest handler on each delivery, so an inline function does not subscribe again on every render.

JavaScript

1

2

3

4

5

6

7

8

9

import { useDeliveries } from '@ably/ai-transport/react';

function Chat() {
  useDeliveries(({ event }) => {
    if (event !== undefined) merge(event);
  });

  return <Messages />;
}

This hook must be used within a TransportProvider.

Subscribing attaches the channel. A failed attach is reported through useTransportStatus.

useDeliveries receives live deliveries only. To replay history before live deliveries, call transport.subscribe with a history option from useTransport.

Parameters

handlerrequired(delivery: Delivery<E>) => void
Called with each delivery, in channel order.
optionsoptionalUseDeliveriesOptions
The provider to read.

The Delivery type:

eventE or undefined
The decoded event, or undefined when the codec produced no event for the message.
messageAbly.InboundMessage
The Ably message as delivered, with its serial, version, clientId, timestamp, action, data and extras.

The hook throws an ErrorInfo with InvalidArgument when no matching TransportProvider encloses the component.

Example

A component tracks which prompt each response answers by the requestId header the agent set on its pipe.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import { useState } from 'react';
import { useDeliveries } from '@ably/ai-transport/react';

function ResponseLog() {
  const [lines, setLines] = useState([]);

  useDeliveries(({ event, message }) => {
    if (event?.type !== 'text-delta') return;
    const requestId = message.extras?.headers?.requestId;
    setLines((prev) => [...prev, `${requestId}: ${event.delta}`]);
  });

  return <pre>{lines.join('\n')}</pre>;
}