react-use-websocket
react-use-websocket copied to clipboard
sending a message on open to the socket in a share connection
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 ?
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/>
);
}