robtaussig / react-use-websocket

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

How to reconnect after reconnect attempt exceeded? #217

Open moonlight3002 opened 1 year ago

moonlight3002 commented 1 year ago

I set usewebsocket on the root of component. If user lost connection and reconnect attempt has exceeded, how can I handle the reconnection?

martin-linden commented 11 months ago

I'm encountering an issue similar to yours. After being offline and the socket instance closes, I need to establish a new socket instance. My current approach involves setting the URL to null and then updating it to my actual URL when attempting to start a new instance. However, this method isn't successful when I try to pass the updated URL to useWebSocket upon regaining connectivity. How can I effectively initiate a new socket instance with the updated URL after the original socket has closed due to an offline period?

danielmcmillan commented 9 months ago

It will reconnect again if the third parameter connect is set to false and then back to true. So one way to do this is to pass some state into the connect parameter, and provide the onReconnectStop callback to set connect state to false. Then setting the state back to true will re-start the connection attempts.

E.g.

  const [connect, setConnect] = useState(true);
  const { readyState, lastJsonMessage, sendJsonMessage } = useWebSocket(
    url,
    {
      onReconnectStop() {
        setConnect(false);
      },
    },
    connect
  );
  const reconnect = useCallback(() => setConnect(true), [setConnect]);
  return <Button onClick={reconnect}>Reconnect</Button>;