John Spiegel
John Spiegel

Reputation: 1903

How to share state between users in ReactJS

I'm building a multiplayer card game mainly in ReactJS and want to share some state between users (players). I need each user to be able to know when it's their turn to play and see some things about other users like score and current number of cards in hand, etc. For example, when one player's turn ends, I need the next player's app to recognize it's their turn and provide the applicable options.

It seems WebSockets or something based on it would be a good option. I'm still learning React and other pieces so I'm trying to keep the number of technologies down for now. I'm considering setting up rapid polling (every 200 ms, perhaps), either to an API or maybe checking against a file on the server or database entries.

Are there especially concerning performance issues or better options to get it working? I'm also learning about AWS and Docker and intend to host on AWS, if possible.

Upvotes: 2

Views: 2419

Answers (4)

Mastacheata
Mastacheata

Reputation: 2061

WebSockets won't work for you as you need one fixed party in WebSocket connection.

You could share the state peer-to-peer style with a WebRTC connection and using the DataChannel in that connection, but that's not an easy task. (see for example: https://www.html5rocks.com/en/tutorials/webrtc/basics/#toc-rtcdatachannel)

The much more common option is to use a central data storage and either sync your state with that or just store it there in the first place. You could use Firebase (see answer by David) or any other kind of database. Firebase is particularly easy to set up, though.

If you have/need/want to use an API-backend anyways, you can use pretty much any kind of database layer in that and just talk REST or GraphQL with the API to share your state between players.

Upvotes: 2

nikhil swami
nikhil swami

Reputation: 2684

instead of sharing state between players you should explore the possibility of players sharing an instance of game object on the server.

for example :

game={
status:'running',
players:2,
p1:{state:'waiting'},
p2:{state:'active'}
}
  • time complexity for common state on server will be [n]

  • expected time complexity for state exchange or polling is [n^2] or more.

Upvotes: 4

bodoroman
bodoroman

Reputation: 278

If you want to try serverless approach, you can look at AWS Lambda and Dynamo DB.

Upvotes: 1

David
David

Reputation: 51

I recommend you use firebase which is a database to send and receive data online because the states of react js are not interlaced between devices

Upvotes: 5

Related Questions