How to keep the React state in sync with MySQL database
Asked Answered
R

1

6

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.

Rusell answered 24/3, 2018 at 21:47 Comment(1)
What have you done so far? It's nice for us to help you with a Minimal, Complete, and Verifiable exampleAntonina
O
6

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

Ondrej answered 24/3, 2018 at 22:11 Comment(1)
Ahh, of course. Thanks for the link and the note about multiple sources making changes. I hadn't thought of that for my prototype here but it will definitely matter to me later :)Rusell

© 2022 - 2024 — McMap. All rights reserved.