Commit 08adf970 authored by tom's avatar tom

better clean-up

parent 8b1723ce
import type { Channel } from 'phoenix'; import type { Channel } from 'phoenix';
import { useContext, useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import notEmpty from 'lib/notEmpty'; import notEmpty from 'lib/notEmpty';
import { SocketContext } from './context'; import { useSocket } from './context';
interface Params { interface Params {
topic: string; topic: string;
...@@ -15,21 +15,29 @@ interface Params { ...@@ -15,21 +15,29 @@ interface Params {
} }
export default function useSocketChannel({ topic, params, isDisabled, onJoin, onSocketClose, onSocketError }: Params) { export default function useSocketChannel({ topic, params, isDisabled, onJoin, onSocketClose, onSocketError }: Params) {
const socket = useContext(SocketContext); const socket = useSocket();
const [ channel, setChannel ] = useState<Channel>(); const [ channel, setChannel ] = useState<Channel>();
const onCloseRef = useRef<string>();
const onErrorRef = useRef<string>();
const onJoinFun = useRef(onJoin); const onJoinFun = useRef(onJoin);
onJoinFun.current = onJoin; onJoinFun.current = onJoin;
useEffect(() => { useEffect(() => {
const onCloseRef = onSocketClose && socket?.onClose(onSocketClose); const cleanUpRefs = () => {
const onErrorRef = onSocketError && socket?.onClose(onSocketError); const refs = [ onCloseRef.current, onErrorRef.current ].filter(notEmpty);
return () => {
const refs = [ onCloseRef, onErrorRef ].filter(notEmpty);
refs.length > 0 && socket?.off(refs); refs.length > 0 && socket?.off(refs);
}; };
}, [ onSocketClose, onSocketError, socket ]);
if (!isDisabled) {
onCloseRef.current = onSocketClose && socket?.onClose(onSocketClose);
onErrorRef.current = onSocketError && socket?.onClose(onSocketError);
} else {
cleanUpRefs();
}
return cleanUpRefs;
}, [ onSocketClose, onSocketError, socket, isDisabled ]);
useEffect(() => { useEffect(() => {
if (isDisabled && channel) { if (isDisabled && channel) {
......
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