-
Notifications
You must be signed in to change notification settings - Fork 55
/
ChannelProvider.tsx
52 lines (45 loc) · 1.55 KB
/
ChannelProvider.tsx
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
import React, { useEffect, useMemo } from 'react';
import * as Ably from 'ably';
import { type AblyContextValue, AblyContext } from './AblyContext.js';
import { channelOptionsWithAgent } from './AblyReactHooks.js';
interface ChannelProviderProps {
ablyId?: string;
channelName: string;
options?: Ably.ChannelOptions;
deriveOptions?: Ably.DeriveOptions;
children?: React.ReactNode | React.ReactNode[] | null;
}
export const ChannelProvider = ({
ablyId = 'default',
channelName,
options,
deriveOptions,
children,
}: ChannelProviderProps) => {
const context = React.useContext(AblyContext);
const { client, _channelNameToChannelContext } = context[ablyId];
if (_channelNameToChannelContext[channelName]) {
throw new Error('You can not use more than one `ChannelProvider` with the same channel name');
}
const derived = Boolean(deriveOptions);
const channel = derived ? client.channels.getDerived(channelName, deriveOptions) : client.channels.get(channelName);
const value: AblyContextValue = useMemo(() => {
return {
...context,
[ablyId]: {
client,
_channelNameToChannelContext: {
..._channelNameToChannelContext,
[channelName]: {
channel,
derived,
},
},
},
};
}, [derived, client, channel, channelName, _channelNameToChannelContext, ablyId, context]);
useEffect(() => {
channel.setOptions(channelOptionsWithAgent(options));
}, [channel, options]);
return <AblyContext.Provider value={value}>{children}</AblyContext.Provider>;
};