1

I am using reactjs and nodejs for my application. I am calling the api created in nodejs in my react js component. Let's suppose, I have a component User. And i am calling api in componentWillMount function to get a list of users. So when a new user is added by add user component, The change is not reflecting to list of users. So i need to use socket.io to make application real time, so that my list of users can get something is updated in database and its time to render the component again.

Is there anything regarding above?

  • You want to addUser and show User RealTime in the same browser? Or like you add user anywhere and you get that user real time? – Supermacy Dec 25 '18 at 10:12
  • Not on same browser. Add user anywhere and get user realtime. –  Dec 25 '18 at 10:50
  • You should try using componentDidMount for on load data and for dynamic update, I don't think it's good unless you are very sure because it uses a lot of bandwidth and would be hard to manage all the clients which are connected to the server. Would be nice if you're looking for a r&d – Leela Venkatesh K Dec 25 '18 at 16:47

2 Answers2

1

You could use Socket.io for updating the users list. Another option is to use server-sent events (for more info on the differences between the two, see this answer).

If you choose to use Socket.io, you can emit an event from the client once a new user is added. Once the server receives that event, it broadcasts it to all other connected sockets (using socket.broadcast.emit). The sockets listen to the users-update event (an example for this can be found here), and once they receive it, the client should update the User component and rerender it.

If you choose to use SSE, check out this article.

Itai Steinherz
  • 777
  • 1
  • 9
  • 19
0

If you want to apply data from response of api to rendered component, I recommend you will call api on componentDidMount. It is the great way. Of course, you can use socket.io

Peng Jin
  • 31
  • 1
  • 4