TransportProvider
TransportProvider creates a transport for one channel and makes it available to the components inside it. It reads the Ably client from the surrounding AblyProvider, so the hooks in @ably/ai-transport/react work in any component it wraps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import * as Ably from 'ably';
import { AblyProvider } from 'ably/react';
import { TransportProvider } from '@ably/ai-transport/react';
import { openai } from '@ably/ai-transport/openai';
const ably = new Ably.Realtime({ authUrl: '/auth' });
export function App() {
return (
<AblyProvider client={ably}>
<TransportProvider channelName="conversations:42" codec={openai}>
<Chat />
</TransportProvider>
</AblyProvider>
);
}TransportProvider must be used within an AblyProvider.
The provider creates the transport after the first render, so useTransport returns transport as undefined on the first render. The provider closes the transport when it unmounts. When the client, the channel name, the codec's adapterTag or the channel modes change, it closes the transport and creates a new one.
The provider also wraps its children in an ably-js ChannelProvider for the same channel, with the options the transport set. So usePresence, useChannel and useChannelStateListener from ably/react work inside it.
To hold more than one conversation, nest providers with different channel names, and pass channelName to a hook to read a specific one.
Properties
channelNameStringcodecCodec<E>vercel from @ably/ai-transport/vercel.channelModesAbly.ChannelMode[]OBJECT_MODES to use LiveObjects on the same channel. The provider compares the modes by their contents, so an inline array that does not change does not recreate the transport.echoMessagesBooleantrue.loggerLoggerchildrenReactNodeIf creating the transport throws, the provider stores the error, and useTransport returns it as error instead of breaking the component tree.
Example
Two providers hold two conversations. A component reads the inner one by default, and the outer one by channel name.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { TransportProvider, useTransport } from '@ably/ai-transport/react';
import { openai } from '@ably/ai-transport/openai';
function Panels() {
return (
<TransportProvider channelName="conversations:support" codec={openai}>
<TransportProvider channelName="conversations:42" codec={openai}>
<Chat />
</TransportProvider>
</TransportProvider>
);
}
function Chat() {
const { transport } = useTransport();
const { transport: support } = useTransport({ channelName: 'conversations:support' });
// ...
}