this is my code snippet bellow, I am trying to close the websocket connection after component unmounts, I just totally dont know how to do it I am using this useEffect inside the same component I am also using useref to count the mounted count of the component so that the websocket doesn't creates more that 1 instance at a time
const mountedCount = useRef(0);
useEffect(() => {
const handleWebsocket = () => {
mountedCount.current ;
const socketURL = 'socket url here'
const socket = new WebSocket(socketURL);
socket.onopen = () => {
console.log('socket open')
};
socket.onclose = (closeEvent) => {
if (closeEvent.wasClean) return;
timeout = setTimeout(() => {
handleWebsocket();
}, envVariables.webSocketReconnectionTimeout);
};
socket.onerror = () => {
console.log('error here')
};
socket.onmessage = (messageEvent) => {
console.log('got the message')
};
return socket;
};
if (mountedCount.current === 0) {
handleWebsocket();
}
return () => {
clearTimeout(timeout);
};
}, [
dispatch,
userData.userInformation,
wss.connectionStatus
]);
CodePudding user response:
const mountedCount = useRef(0);
const [currentSocket,setCurrentSocket]=useState(null)
useEffect(() => {
const handleWebsocket = () => {
mountedCount.current ;
const socketURL = 'socket url here'
const socket = new WebSocket(socketURL);
socket.onopen = () => {
console.log('socket open')
};
socket.onclose = (closeEvent) => {
if (closeEvent.wasClean) return;
timeout = setTimeout(() => {
handleWebsocket();
}, envVariables.webSocketReconnectionTimeout);
};
socket.onerror = () => {
console.log('error here')
};
socket.onmessage = (messageEvent) => {
console.log('got the message')
};
return socket;
};
if (mountedCount.current === 0) {
setCurrentSocket(handleWebsocket());
}
return () => {
clearTimeout(timeout);
currentSocket?.close();
};
}, [
dispatch,
userData.userInformation,
wss.connectionStatus
]);
CodePudding user response:
or you can declare socket variable in one upper scope:
const mountedCount = useRef(0);
useEffect(() => {
let socket
const handleWebsocket = () => {
mountedCount.current ;
const socketURL = 'socket url here'
socket = new WebSocket(socketURL);
socket.onopen = () => {
console.log('socket open')
};
socket.onclose = (closeEvent) => {
if (closeEvent.wasClean) return;
timeout = setTimeout(() => {
handleWebsocket();
}, envVariables.webSocketReconnectionTimeout);
};
socket.onerror = () => {
console.log('error here')
};
socket.onmessage = (messageEvent) => {
console.log('got the message')
};
return socket;
};
if (mountedCount.current === 0) {
handleWebsocket();
}
return () => {
clearTimeout(timeout);
socket.close()
};
}, [
dispatch,
userData.userInformation,
wss.connectionStatus
]);