Home > Net >  Struggling with typescript in chat application using socket.io
Struggling with typescript in chat application using socket.io

Time:11-12

I am building a real-time notification app using socket.io and typescript and when I am trying to send event from client to server it shows an error. Below is my code when I am updating my state it shows an error in the browser window that "Cannot read properties of null (reading 'emit')"

  const [socket, setSocket] = useState<any>(null)

  useEffect(()=>{
    setSocket(io("http://localhost:5000"));
   
  },[])

  useEffect(()=>{
    socket.emit("newUser", user);
  },[socket,user])

CodePudding user response:

Most likely, your emit fails because you call it too soon, before your connection is established.

socket.on("connect", () => {
  console.log(socket.id); // x8WIv7-mJelg7on_ALbx
  socket.emit("hello", { a: "b", c: [] });
});
  • Related