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?

3
  • 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? Commented Dec 25, 2018 at 10:12
  • Not on same browser. Add user anywhere and get user realtime. Commented Dec 25, 2018 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 Commented Dec 25, 2018 at 16:47

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In Server Sent Events there connection is also maintained between server and client.
Thanks for the correction. I've revised my comment accordingly.
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

1 Comment

I am asking, how can i use socket.io with react and nodejs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.