robtaussig / react-use-websocket

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

Feature request: Allow for manually triggering a reconnect #208

Closed ElectricCoffee closed 1 year ago

ElectricCoffee commented 1 year ago

As it stands (from what I understand reading the API). You can add a shouldReconnect function which automatically triggers when the socket receives an close event.

That said, it would be really nice to allow the library user to manually trigger a reconnect, or heck, manually triggering opening.

Possible use-case would to close the connection when streaming is no longer needed, and then providing a button for the user to press to reinitiate the stream

robtaussig commented 1 year ago

You should be able to do this by using the third param to indicate connection intent! Bind it to a useState variable and set it to true/false based on that button click (or whatever logic determines when streaming is no longer needed)

ElectricCoffee commented 1 year ago

((apologies for late response, I was on vacation))

Does setting it to false also close the connection?

That is, implying the state variable is set to true by default; would clicking the button and setting it to false then close the stream?

robtaussig commented 1 year ago

@ElectricCoffee yes, it will close the connection (if it’s not a shared websocket). If you are using the share functionality, then it will only close the connection once all “subscribers” have unmounted/passed false for that param