What is the correct way to structure a websocket connection within a React app where the socket port is loaded via a RESTful call on page load?
- User loads React App
- RESTful GET request for socket port (fetch) E.g. http://example.com:1234/port //-> { "port": 9999 }
- Construct websocket URI from response
- Connect (Native ws or socket.io-connect)
- Set up callbacks (onmessage)
- Monitor connection status. Attempt to reconnect if disconnected
...all within a functional app.
The main problems are:
the synchronization of the RESTful call for the ws port. Here I am considering a promise [Ref 0]?
The socket reconnecting on each render. Calls in the
onmessage
use hooks, and so must be in the function body. Here possibly a ws status check before a reconnect? [Ref 1]
How is this properly structured?
I'm also considering a separate class or function dedicated to handling the ws connection.