Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to reconnect after reconnect attempt exceeded? #217

Open
moonlight3002 opened this issue Nov 2, 2023 · 2 comments
Open

How to reconnect after reconnect attempt exceeded? #217

moonlight3002 opened this issue Nov 2, 2023 · 2 comments

Comments

@moonlight3002
Copy link

moonlight3002 commented Nov 2, 2023

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
Copy link

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
Copy link

danielmcmillan commented Feb 11, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants