If you read my last blog post on optimistic rendering then you know once you’ve appended something to the page optimistically it will not survive a refresh. This is because the data has not persisted. To persist your data means that you add it to your database. In my previous blog I used one of my old projects as an example and in this post I will continue off of that to display fetch calls. To persist data you will need to use fetch calls. In my project I make a fetch to my backend with the endpoint in which I want to add data:
Fetch calls return a promise, a promise is an eventual value. The handle response method here is a function that takes the incoming data which is in JSON format and parses it. After this fetch I build my showDogs function that optimistically renders and persists data to the backend. Since this blog is one about fetch calls and persisting data I’m gonna skip over the explanation of the other code involved in this function and get right to the fetch call. Heres the part of this function that handles optimistically rendering:
and heres the code that handles persisting the data to the database:
As you can see here the fetch call is FETCHing my backend to the endpoint of dog breeds (/breeds). The RESTful method that is used is a POST. The reason the data persists is because this method in this fetch call makes a post to the backends database and adds the new information to it. In the headers section the ‘Content-Type’ is JSON. In the body of this fetch call we are stringify-ing the data being received. Stringify converts an object or a value to a JSON string, and in this example the values are from the form data in the picture above which come from users input on a form.
After this fetch call a post method will add whatever was submitted on the form to the database in the backend and the data will persist and survive a refresh of the page. Another thing for this to work is this needs to be inside of an event listener, in this example the event listener was a submit. The submit event listener was put on the submit button that is connected to the form via the HTML.