robtaussig / react-use-websocket

React Hook for WebSocket communication
MIT License
1.6k stars 136 forks source link

RetryInterval ignored for shared = true #74

Closed brandonm closed 3 years ago

brandonm commented 3 years ago

I have a simple Spring Websocket server that will close a connection when an unknown connection is connected. When I have this lib setup with share: true then reconnectInterval is ignored and it will immediately reconnect. When shared is false it is waiting. I do use an async url request promise that will generate a new url on each connection attempt but I'm assuming its the incrementer that isn't behaving correctly for shared, somewhere around:

https://github.com/robtaussig/react-use-websocket/blob/9b0b70c4cc6654caff77a0e07fa75c8af70b2172/src/lib/attach-shared-listeners.ts#L65

{ 
       ...,
       share: false,
       shouldReconnect: () => {
            return didUnmount.current === false;
        },
        reconnectAttempts: 5,
        reconnectInterval: 10000,
        retryOnError: true
}
robtaussig commented 3 years ago

Thanks for bringing this to my attention. Will investigate.

robtaussig commented 3 years ago

Hi @brandonm,

It's been a while since any work was done on that particular code, and while I am certainly capable of dumb mistakes, it does look like it might have been intentional to fire off the first reconnect attempt immediately for shared websockets (otherwise, why use the conditional at all?). Since this is both counter-intuitive to how intervals typically work as well as different from how non-shared websockets reconnect, I made the straight forward fix with 75d7e6c. That said, out of caution for breaking something that was 'fixed' by that logic, I have tagged this release as beta: https://www.npmjs.com/package/react-use-websocket/v/2.5.0-beta.0

Thanks again for bringing this up and especially for taking the time to identify where in the code this was caused. I'll be testing this change with a few projects of mine that use shared websockets, but if you happen to have a chance to do so as well, I would be very appreciative!

robtaussig commented 3 years ago

Released to 2.5.0. Thank you for your feedback!