user10742206
user10742206

Reputation:

Use socket.io in react and node js application

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?

Upvotes: 1

Views: 365

Answers (2)

Itai Steinherz
Itai Steinherz

Reputation: 807

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.

Upvotes: 1

Peng Jin
Peng Jin

Reputation: 31

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

Upvotes: 0

Related Questions