Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to have the socket object in your redux app? [closed]

I'm working on a chat application using react, redux and socket.io. As we know, redux is very helpful to pass down some state to deep and nested components. I like this idea to store some props as a redux state which will be passed down to some heavily nested component. I'm using socket.io-client library to create the socket object.

I need to pass down the created socket object to some heavily nested components so, I was thinking of creating the socket object on the redux state so that I can consume it easily on the nested components.

Is this a good approach or should I be doing something else?

like image 998
Aziz Avatar asked Sep 15 '18 13:09

Aziz


People also ask

Where is Redux data stored?

The state in Redux is stored in memory. This means that, if you refresh the page the state gets wiped out. The state in redux is just a variable that persists in memory because it is referenced by all redux functions.

How do you link a WebSocket in React?

We connect the WebSocket server to the HTTP port when it's been created: const webSocketServer = require('websocket'). server; const http = require('http'); const webSocketServerPort = 8000; // Start the http server and the websocket server const server = http. createServer(); server.


1 Answers

No, it's not.

We recently added a Redux FAQ entry on where websockets should live in a Redux app. Quoting that entry:

Middleware are the right place for persistent connections like websockets in a Redux app, for several reasons:

  • Middleware exist for the lifetime of the application
  • Like with the store itself, you probably only need a single instance of a given connection that the whole app can use
  • Middleware can see all dispatched actions and dispatch actions themselves. This means a middleware can take dispatched actions and turn those into messages sent over the websocket, and dispatch new actions when a message is received over the websocket.
  • A websocket connection instance isn't serializable, so it doesn't belong in the store state itself
like image 169
markerikson Avatar answered Oct 26 '22 13:10

markerikson