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

How to reconnect after reconnect attempt exceeded?

Open moonlight3002 opened this issue 1 year ago • 2 comments

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

moonlight3002 avatar Nov 02 '23 07:11 moonlight3002

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?

martin-linden avatar Dec 19 '23 14:12 martin-linden

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>;

danielmcmillan avatar Feb 11 '24 07:02 danielmcmillan