socket.io-client
socket.io-client copied to clipboard
Handling Hot-Module-Reloads in Development Environments
This is more of a documentation addition request rather than a bug or feature request.
I'm building an Electron-based application using React, and I was having issues with too many sockets being requested until I had the epiphany that websockets are bound to the window
lifecycle which was causing this behavior whenever the hot module reload (HMR) feature of my development environment was triggered.
Upon a fresh reload (or initial launch) of the application, the componentDidMount
method of the base application component calls a method that initiated the socket.io
connection and all is good. However, after saving a file whilst working, the HMR is triggered and the entire application refreshes with the changes, and with this reload the same method is called again, which opens a additional websocket connection, even though one already exists (because the HMR doesn't reload the actual window
object).
My solution was to save the reference to the socket returned from the io(url, options)
function in the window
object and only open the new connection if the returned value is null or undefined.
This was driving me nuts for the better part of the day, until I realized that the connection is still alive and unaffected between HMR events. An obvious conclusion to be sure, but one that just did not occur to me straight away.
Can I suggest that somewhere in your docs that mentions this, so others in the future don't pull their hair out like I did? And is this the best way to do this? Or is there some utility method/function somewhere that can be used to get open sockets?
Ta
https://socket.io/how-to/use-with-vue#hot-module-reloading https://socket.io/how-to/use-with-react#hot-module-reloading
These things are now documented.
I think this can be closed now. Please reopen if needed.