Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
139
rated 0 times [  143] [ 4]  / answers: 1 / hits: 18438  / 8 Years ago, sun, march 20, 2016, 12:00:00

I'm new to React and I'm having some issues regarding components structure and sharing a websocket between them.



The app consists of categories and products. The initial data load will be done with an Ajax request and a websocket will be used keep data updated.



My component hierarchy looks like this:




  • CategoriesList


    • Category


      • ProductsList


        • Product






CategoriesList holds the state of categories and ProductsList holds the state of products within a category.



So I would like to use the same websocket inside CategoriesList and ProductsList but listening to different websocket events: category:updated and product:updated.



How do I share the websocket between components and where is the right place to initialize it?



Since there is one ProductsList for each Category, does this means that the products:updated event will fire multiple times ( one for each category )? I guess this isn't a good thing in terms of performance.


More From » reactjs

 Answers
14

I recommend initializing your socket connection in CategoriesList and then passing down the connection as props to the child components. When the connection is passed down, you should be able to use it to listen for specific events as needed in the child components.



Here's an example application on github that uses react and socket.io. The socket is initialized in a parent component and then passed down. https://github.com/raineroviir/react-redux-socketio-chat/blob/master/src/common/containers/ChatContainer.js



On line 9 the connection is initialized and then on line 23 it's passed down as props. The connection is later used in child components to receive and emit events. Ex: https://github.com/raineroviir/react-redux-socketio-chat/blob/master/src/common/components/Chat.js


[#62869] Thursday, March 17, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
markusdamienn

Total Points: 167
Total Questions: 119
Total Answers: 93

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;