How to use websockets in react life cycle methods?


I’m trying to use WebSockets in react life cycle methods respectively. With the following code, only the initial function call when a component mounts the first time. then Inside componentdidupdate method. I’m calling send and receive functions I made in sockets. You can trace code success by console messages in the picture below.

import {initiateSocketAndSend,sendMessage,ReceiveMessage,disconnectSocket,onError} from '../scokets/sockets';

      componentDidMount(){
        
         initiateSocketAndSend()
      }

      componentDidUpdate(){
        sendMessage(this.props)
        ReceiveMessage()
        onError()
        disconnectSocket()
      }

      componentWillUnmount(){
        disconnectSocket()
      }

sockets.js

let ws;

export const initiateSocketAndSend = () => {
   ws = new WebSocket("ws://localhost:8000/ws/projects/test_key");
   // alert("conneted")
   console.log("connected")
}


export const sendMessage = (props) => {
   console.log("send",ws) //Reaching here
   ws.onopen = function() {
      // Web Socket is connected, send data using send()
      // console.log("do somethimg") // Not reaching here
      const send_object = JSON.stringify(props)
      // console.log("user",send_object)
      ws.send(send_object);
      console.log("Message is sent...")

   };

   // ws.onopen = function (event) {
   //    console.log("do somethimg") //Not 
   //    ws.send("Here's some text that the server is urgently awaiting!");
   //  };
}

export const ReceiveMessage = () => {

   // Web Socket is connected, receive data
   ws.onmessage = function (event) {
      const data = JSON.parse(event.data);
         console.log(data["message"])
   };
}

export const onError = () => {
   ws.onerror = function(event) {
      console.log(event);
    }
}

export const disconnectSocket = () => {
   ws.onclose = function() {     
      // websocket is closed.
      console.log("Connection is closed...")
   };
}

enter image description here

Source: JavaSript – Stack Overflow

November 8, 2021
Category : News
Tags: django-channels | javascript | reactjs | sockets | websocket

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.