Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the React state in sync with MySQL database

Tags:

Scene: I am building a simple calendar web-app that uses React for the front-end and MySQL on the back-end for the server. The app retrieves a list of all the events from the server when it is first mounted, displays them to the user and allows for CRUD operations. Everything works as expected.

Question: On a Create, Update or Delete operation, should I:

  1. Update the database and the state "independently".

  2. Update the database, make another call to the server to retrieve the new list of events and then set the state equal to this new list.

  3. Do something else entirely.

Impetus: I am working under the impression that there should be a "single source of truth" for my data, and it feels likes the first option above creates a situation where I have two "sources" that could in some situation become out of sync.

like image 893
lukeoleson Avatar asked Mar 24 '18 21:03

lukeoleson


1 Answers

Both 1. and 2. are correct, it really depends on what are you trying to achieve. You can try to use optimistic updates which means that when submitting these operations you change the state as if it was successful (which should be the case most of the time) and make a correction if the operation failed in the database/backend for some reason. This creates a nice front-end experience. In these cases you can also get the new data after the operation.

If the data on the database can change from multiple sources, you need to get it periodically and after changes most probably, and update your front-end accordingly.

Case 1. should work if you are the only one manipulating the data (which you need to have in the state at least). In this case the back-end / database should still respond with the status of the performed operation in order to help you manage the state. You can also display some kind of loading indicator while the operation is pending instead of optimisticaly updating the state.

You can read more about optimistic updates here: https://medium.com/guidesmiths-dev/anatomy-of-a-react-application-optimistic-updates-e4a3318665c7

like image 51
Ankari Avatar answered Sep 19 '22 13:09

Ankari