Search code examples
node.jsreduxsocket.io

Can I store socket.io socket in redux store? (and call its functions)


I am trying to store a socket created for the client in App.js in my Redux store? I am not sure if this is even a good idea or not, but I want to be able to access the same socket in multiple components, so I thought I could just do it like I did with other objects.

Howerever, the things I stored until now in my redux store are strictly objects with fields in them, I have never stored an object that had functions.

When I try to call a function of the stored socket, I get: TypeError: this.props.socket.emit is not a function.

Which I guess means that I can't store class entities using Redux. Is this correct?

What would be the right solution here?


Solution

  • The best method to do something like this would be to isolate all code that deals with sockets and expose only those functions that your components call (something like socket.send(message: string) to send message etc).

    Don't worry about importing the same module/file again and again, as no matter how many times you import/require it, the same instance is returned. So it's safe to isolate the socket functions and import them wherever needed.

    Also, Redux is a state management library, therefore please don't expect it to handle functions and other advanced functionality.