ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Thursday, November 24, 2022

[FIXED] How to turn off the websocket after component unmounts

 November 24, 2022     javascript, next.js, reactjs, typescript, websocket   

Issue

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
]);

Solution

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
]);


Answered By - Kamran Davar
Answer Checked By - - Terry (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix