Files
explore/lib/socket/useSocketChannel.tsx
T
Igor StuevandGitHub 1c9c4e48d5 zeta chain cctx (#2904)
* zetachain start

* zeta chain cctx table

* pagination

* cctx page init

* meta for new route

* remove backlink

* schema

* continue

* fix

* navigation

* filters to test

* some fixes

* add chain filter

* add error message and revert options

* address chain logo fix

* cctx search

* socket

* fix conflict

* fixes1

* fixes2

* fixes3

* fixes4

* fixes5

* tests

* fixes6

* test fixes

* revert options fix

* stats and revert semi-fix

* fix readme

* cleanup

* check for cctx in lifecycle

* update config

* fixes 8

* fixes 9

* update config

* fixes10
2025-09-05 15:53:00 +02:00

87 lines
2.4 KiB
TypeScript

import type { Channel } from 'phoenix';
import { useEffect, useRef, useState } from 'react';
import { useSocket } from './context';
interface Params {
topic: string | undefined;
params?: object;
isDisabled: boolean;
onJoin?: (channel: Channel, message: unknown) => void;
onSocketClose?: () => void;
onSocketError?: () => void;
socketName?: string;
}
export default function useSocketChannel({ topic, params, isDisabled, onJoin, onSocketClose, onSocketError, socketName }: Params) {
const { socket, channelRegistry } = useSocket(socketName) || {};
const [ channel, setChannel ] = useState<Channel>();
const onCloseRef = useRef<string>(undefined);
const onErrorRef = useRef<string>(undefined);
const onJoinRef = useRef(onJoin);
onJoinRef.current = onJoin;
useEffect(() => {
const cleanUpRefs = () => {
const refs = [ onCloseRef.current, onErrorRef.current ].filter(Boolean);
refs.length > 0 && socket?.off(refs);
};
if (!isDisabled) {
onCloseRef.current = onSocketClose && socket?.onClose(onSocketClose);
onErrorRef.current = onSocketError && socket?.onError(onSocketError);
} else {
cleanUpRefs();
}
return cleanUpRefs;
}, [ onSocketClose, onSocketError, socket, isDisabled ]);
useEffect(() => {
if (isDisabled && channel) {
channel.leave();
setChannel(undefined);
}
}, [ channel, isDisabled ]);
useEffect(() => {
if (!socket || isDisabled || !topic || !channelRegistry) {
return;
}
let ch: Channel;
if (channelRegistry.current[topic]) {
ch = channelRegistry.current[topic].channel;
channelRegistry.current[topic].subscribers++;
onJoinRef.current?.(ch, '');
} else {
ch = socket.channel(topic);
channelRegistry.current[topic] = { channel: ch, subscribers: 1 };
ch.join()
.receive('ok', (message) => onJoinRef.current?.(ch, message))
.receive('error', () => {
onSocketError?.();
});
}
setChannel(ch);
const currentRegistry = channelRegistry.current;
return () => {
if (currentRegistry[topic]) {
currentRegistry[topic].subscribers > 0 && currentRegistry[topic].subscribers--;
if (currentRegistry[topic].subscribers === 0) {
ch.leave();
delete currentRegistry[topic];
}
}
setChannel(undefined);
};
}, [ socket, topic, params, isDisabled, onSocketError, channelRegistry ]);
return channel;
}