Flux
Flux

Reputation: 77

Reconnection of websocket after browser reload

I am creating a react app that has a lot of components which mimic real life controls such as switches, temperature controllers, sensors, pir's etc and is heavily reliant on state

Initially a connection to the server pulls in a json list of controls, which is parsed, rendered and displayed by the app. Unwanted reloads of this file is managed by checking its version date which is held in local storage.

Once loaded a call is then made to download the initial states of ALL the controls which can take a few seconds to receive, construct and render. Subsequently but within the same command only states that are changed are received and processed

Now here is the crux of the matter. All works fine up until the point whereby the app is refreshed. I understand that when a browser is refreshed any web socket that is open is closed and reconnected (using the same code) however upon reconnection due to the fact that I have a new connection to the server i cannot receive only updated states but am forced to download and parse all of the control states again,

I have tried looking into using logic to check if a socket is open before sending the initial command but from what I understand of how a web socket works this will not work,

Is there any way I can store the Id of the websocket as a cookie (of which I know nothing about) or in local storage to reconnect the same socket connection after reload thus allowing only new state changes to be received.

If not fesible then any recommendations on how to better manage having to constantly load and parse all the controls every time.

Upvotes: 1

Views: 2054

Answers (1)

O. Jones
O. Jones

Reputation: 108641

As you know browsers slam websocket connections shut on page unload. And, after reloading any state stashed in the DOM is gone.

When the browser slams the the websocket, the server is notified it's closed. Therefore, your websocket connection is gone gone gone after reload. You need to set up a new one. You won't be able to find the old one.

You may be able to use local storage or session storage to hold your application's state (not just the timestamp of the most recent retrieval). Then after reload your application can fetch the state from that storage, rather than having to repopulate it from scratch from your server over your websocket channel.

You can try listening for an 'unload' event on your app's document.defaultView window, and making your event handler store your status in local or session storage before the page unloads.

Obviously, you're caching your app state in your browser when you do this. So you take on the problems of cache consistency, time-to-live, stale data, and all that.

The 'toobz have plenty of examples of using React/Redux with local/session storage.

Upvotes: 1

Related Questions