0

I have a react js, node js and mongoDB application. I have a collection in mongoDB.

Senario : Let's say there are 3 users (A, B, C) login in same time. All of them are accessing same collection in same time. Let C changed something in the collection from UI.

  1. So how A and B can access those changes done by C in UI in same time ?
  2. And in this senario what should be the best approach ?
Sangram Badi
  • 4,054
  • 9
  • 45
  • 78
  • 3
    You mean you want the changes to be *live updating* on everybody's screen? Consider trying socket.io – TKoL Apr 25 '18 at 07:22
  • An alternative will be potentially the client redownloading the entire collection periodically and checking for changes, depending on the size of the collection, or somewhere storing the last updated date of the collection, and if that date is later than their latest refresh, redownloading the data then. – TKoL Apr 25 '18 at 07:23
  • @TKoL for nodejs is there any plugin for socket.io or have already in nodejs ? – Sangram Badi Apr 25 '18 at 08:12
  • https://www.npmjs.com/package/socket.io – TKoL Apr 25 '18 at 09:22

2 Answers2

3

An easiest solution should be to use webSocket (you can try socketIo). In that way you tell to all of your users in your app to "listen" some changes. As an example in a ToDo list User C will add a todo item, server is notified of this adding, and will emit through web socket to all users listening to this particular event. socket.io. Hope my answer will be helpful.

There is several ways to use Socket.io. You can emit from the client to the server, and server will emit to the other clients. Example :

client Side (user adding a ToDo): socket.emit('message', YourTODOVariable);
Server Side: socket.on('message',function(YourTODOVariable){
//do other stuff here;
socket.broadcast.to('ToDo', YourTODOVariable)
})
Client Side (other Users): socket.on('ToDo', function(YourTODOVariable){
ToDo.push(YourTODOVariable) //-> like this everybody got the new variable.
})

I assume it's quite a simple example but I think you can understand with this.

Another solution which I prefer personally is to correlate to node event. As an example a new Http request will fire a node event and will fire a socket.emit to all other client listening.

This post can also help you. Happy coding :)

cagliostro
  • 182
  • 1
  • 10
1

So there are multiple solutions for your scenario , for example:

  1. Socket.IO: In this solution you would have to manage all clients-sockets and once the server emits a message, all registered clients would be notified.

  2. React Redux: Sample your database every x-milliseconds, and update the store-state in your app, so all registered components to the state will get update once change was mad. (this is a more flatten solution than option 1. but a little ugly)

Nirit Levi
  • 251
  • 1
  • 7