Home > Net >  Can I force react to rerender when other user is inserting data into database?
Can I force react to rerender when other user is inserting data into database?

Time:08-22

I would like to create simple forum where users would be able to add/delete/modify posts stored in database. I have simple auth app: client(react app) - server(express). Is it possible to force client side to rerender for one user when there is a change made by another user while both are loggedIn?

CodePudding user response:

It should be simple enough. When a logged in user is on a page that you want to keep synced, open a websocket to the server. Then, when any user makes a change, the server can update its database, and then once that's finished, it can send a websocket message to all users with connected sockets on that page, containing the new data to render.

In the client-side React, create the socket and subscribe to its message event. When a message is sent from the server, call the state setter with the new data.

This mechanism is somewhat similar to how Stack Overflow pushes "An edit has been made to this post" notifications when a post gets edited - anyone looking at the page will see such server-sent notifications through the websocket connection to Stack Exchange.

CodePudding user response:

Websockets is one approach you can follow. If you think this will be complex to implement, you can poll for the data every minute or so.

This is very useful library tailored for React: useQuery- https://tanstack.com/query/v4/docs/reference/useQuery?from=reactQueryV3&original=https://react-query-v3.tanstack.com/reference/useQuery

You can use it for polling/caching and making regular network calls as well. Lots of utility is provided that you can leverage; especially, considering the use case you seem to be tackling. There is a slight learning curve, but its worth it if you're a react developer.

  • Related