Optimistic Rendering from a form in React
We use forms to allow the user to alter something on the website/app. Sometimes this is change occurs on the backend, other times it’s only something the user sees immediately, but what if the form alters both the backend AND the immediate display?
On the project I’m working on, there is a page where the user can keep track of species of fish they’ve caught and their personal record (longest fish) for each of these species’ they’ve encountered.
The form that appears once a fish is listed as “caught” allows the user to update their current personal record for a given fish. Upon filling out the form the “Biggest Catch” H3 item on the card should immediately update.
Prior to being updated this value is set as 0, as it is taken from from my rails backend, and set to state.
After this on the form, the value of the text input is set equal to the current state, and an on change function is called each time the user types anything in the input box.
The handleChange then updates the state accordingly. Once state is updated the H3 tag with “Biggest Catch 0 in.” gets immediately updated in the render.
Above, you can see how even before hitting submit, that the h3 on the fish card is now updated!
But if we refresh this page, we want this value to remain on the page. After all, there’s no point in typing your personal record if the website isn’t even going to record it. This is where the submit button comes in!
On our form we are going to want our submit button to update your biggest catch on the backend. To do this, we are going to use a handleSubmit function as a sort of control center that will call a bunch of other functions.
Once handleSubmit is called by clicking “Submit Size”, three other functions will run.
1) There’s a prevent default because we don’t want the page to reload, simply because we clicked submit.
2) prFrontend sets the state as the value most recently entered. (This is sort of unnecessary, since state is already changed each time the user types anything in the input box. However, I’m including it here to emphasize that we want the state set first, before the backend is altered).
3) prBackend calls a fetch request to update or ‘patch’ our rails backend so that the given fish’s PR is permanently altered. Now, even when we leave the page and come back the site will know what all of our personal record’s are!