Commit 07c4deb5 authored by tom's avatar tom

multiple channel subscriberes on one page

parent 1b6eb9cc
...@@ -5,6 +5,8 @@ import notEmpty from 'lib/notEmpty'; ...@@ -5,6 +5,8 @@ import notEmpty from 'lib/notEmpty';
import { useSocket } from './context'; import { useSocket } from './context';
const CHANNEL_REGISTRY: Record<string, Channel> = {};
interface Params { interface Params {
topic: string | undefined; topic: string | undefined;
params?: object; params?: object;
...@@ -51,12 +53,21 @@ export default function useSocketChannel({ topic, params, isDisabled, onJoin, on ...@@ -51,12 +53,21 @@ export default function useSocketChannel({ topic, params, isDisabled, onJoin, on
return; return;
} }
const ch = socket.channel(topic, params); let ch: Channel;
ch.join().receive('ok', (message) => onJoinRef.current?.(ch, message)); if (CHANNEL_REGISTRY[topic]) {
ch = CHANNEL_REGISTRY[topic];
onJoinRef.current?.(ch, '');
} else {
ch = socket.channel(topic);
CHANNEL_REGISTRY[topic] = ch;
ch.join().receive('ok', (message) => onJoinRef.current?.(ch, message));
}
setChannel(ch); setChannel(ch);
return () => { return () => {
ch.leave(); ch.leave();
delete CHANNEL_REGISTRY[topic];
setChannel(undefined); setChannel(undefined);
}; };
}, [ socket, topic, params, isDisabled ]); }, [ socket, topic, params, isDisabled ]);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment