skip to Main Content

I am making a web app where i want to show online/offline status of user. For that i need to listen to close and open events of websocket.

const ws = new WebSocket('ws_url', 'token');
ws.onclose = (e) => {
   const data = {
     type: "offline",
     userId: "someid"
   }
   ws.send(JSON.stringify(data))
}

2

Answers


  1. Using useEffect you can pass the functions on component destroy, just use "return" isnide https://react.dev/reference/react/useEffect#usage

    Login or Signup to reply.
  2. • You have create a function first to handle the WebSocket close event and send your data. You already have this part in your code:

    const handleWebSocketClose = () => {
      const data = {
        type: "offline",
        userId: "someid"
      };
      ws.send(JSON.stringify(data));
    };
    

    • you can use the beforeunload event to call this function

    import { useEffect } from 'react';
    
    function YourComponent() {
      useEffect(() => {
        // Add an event listener for beforeunload
        window.addEventListener('beforeunload', handleWebSocketClose);
    
        // Clean up the event listener when the component unmounts
        return () => {
          window.removeEventListener('beforeunload', handleWebSocketClose);
        };
      }, []);
    
      // Your component logic here...
    
      return (
        // Your component JSX here...
      );
    }
    
    export default YourComponent;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search