robtaussig / react-use-websocket

React Hook for WebSocket communication
MIT License
1.63k stars 135 forks source link

How to subscribe to channel #114

Closed Robokishan closed 2 years ago

Robokishan commented 2 years ago

Hey I see docs how to use it properly. there are some docs regarding subscribe. but i can't find how to implement it using this library can somebody provide me link or any implementation for subscribing to websocket events. because when tried to connect to websocket server it correctly connecting. but it is not sending any probe. after success-full connection it just disconnects. i am not sure what is causing this issue but let me know if someone can help me with that. Thanks! best library so far for websocket react.

PS: I don't want to send messages. i want subscribe to specific topic and then put event listener to that. something like call back function.

i tried getwebsocket which is returned by hook but it is giving me error. Screenshot 2021-12-01 at 5 51 03 PM

robtaussig commented 2 years ago

Hi @Robokishan,

There is no native subscribe for WebSockets -- this is something you need to implement yourself based on a coordination of messages between the client and a server. An example:

On the client:

  useWebSocket('some-url', {
    onMessage: (message) => {
      try {
        const messageData = JSON.parse(message.data);
        switch(messageData?.eventType) { //eventType is a property defined from the server message and not something that exists on all websocket messages
          case 'EVENT_1':
            //Handle 'EVENT_1';
            break;
          case 'EVENT_2':
            //etc
          default:
            //unknown event -- throw error?
        }
      } catch (e) {
        // message.data is likely not parseable
      }
    }
  })

As for sending a probe, this is also something that must be handled by you:

    const { sendMessage, readyState } = useWebSocket('some-url');

    useEffect(() => {
      if (readyState === 1) {
        sendMessage('1'); //Or whatever your agreed upon probe looks like
      }
    }, [readyState, sendMessage]);

If you are coming from a codebase that needs to work with a socket.io backend, which does require special heartbeat handling, then you should try the useSocketIO helper hook

siddharthkul commented 1 year ago

Hi @robtaussig, adding this issue here since it is slightly related on the sending part - https://github.com/robtaussig/react-use-websocket/issues/173