react-use-websocket icon indicating copy to clipboard operation
react-use-websocket copied to clipboard

sending a message on open to the socket in a share connection

Open cubecleveland opened this issue 2 years ago • 1 comments

Hi, We have a share connection socket. We share it through the app. I want to send a message on socket open but not sure whihc methid to use ( can not use getWebsocket().send because of the share and dont have access to the sendMessage function...

Any suggestions ?

EDIT:

this also begs the question if there is any way to make a shared connection where 1 compoenent is the parent that can access the socket ?

cubecleveland avatar Mar 01 '22 17:03 cubecleveland

Hi @cubecleveland,

What I would do in this situation is send the message from a parent component (or any component of which yo know there can only be one):

const Parent = () => {
  const { sendMessage, readyState } = useWebSocket('wss://websocket-url.com', { share: true });

  useEffect(() => {
    if (readyState === 1) {
      sendMessage('This should only get sent once when the socket opens');
    }
  }, [readyState, sendMessage])
  return (
    <div>
      <Child/>
      <Child/>
    </div>
  )
}

const Child = () => {
  useWebSocket('wss://websocket-url.com', { share: true });
  return (
    <div/>
  );
}

robtaussig avatar May 17 '22 14:05 robtaussig