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

Websocket closes automatically without reconnect - check my own custom hook which reuses this lib

Open ebasic opened this issue 2 years ago • 0 comments

Hi folks,

I will provide my implementation of websocket using react-use-websocket lib, and here are questions?

  • Should I subscribe in useEffect as it is, or I can move subscribe() call into onOpen listener?
  • Does it automatically reconnect internally or I have to do something additional?
  • Why sometimes it closes automatically without reconnect? Did I miss something or?
  • How can I integrate "ping" feature here with inteval?
  const useWebSocketData = () => {
     const [data, setData] = useState([]);
   
     const { lastMessage, readyState, sendJsonMessage } = useWebSocket(config.websocketUrl, {
       onOpen: () => {
         console.log('open');
       },
       shouldReconnect: () => true,
       onClose: () => {
         console.log('close');
       },
       reconnectAttempts: 10,
       reconnectInterval: 5,
       retryOnError: true,
     });
   
     const subscribe = useCallback(
       () => sendJsonMessage({ id: 'someId', topic: 'someTopic', event: 'sub', params: { binary: false } }),
       [sendJsonMessage]
     );
   
     useEffect(() => {
       if (readyState === ReadyState.OPEN) {
         subscribe();
       }
     }, [readyState]);
   
     useEffect(() => {
       if (lastMessage?.data) {
         const parsedData = JSON.parse(lastMessage.data);
   
        setData((prev) => prev.concat(parsedData));
       }
     }, [lastMessage, setData]);
   
     return {
       data,
       readyState,
     };
   };

ebasic avatar Apr 06 '23 21:04 ebasic