I hope that you will find this writing useful and maybe use auto save for one of your projects. Proper solution would be to use one of the approaches that I already mentioned at the beginning - drafts, "forward" revisions. One way to solve this would be to save an empty post before loading the form, which is obviously not ideal. What about new posts? Our approach assumes that the post already exists in the database and this is not the case on the create form.
We will also need to update a few things in our project to be able to use it. Check LiveView's page on hex.pm for up to date information. This was the most recent version at the time of writing. There will be no juice without the LiveView, so let's bring it in by adding it to mix.exs: #.
If you are not sure how to get this far check Phoenix documentation.
I decided to go with a Post with title and body (but we could use any number or type of fields): #. We need a new Phoenix project with a schema that we'll work with.
If you already know how LiveView works feel free to skip to the interesting part. I also created a GitHub repo where you can see the working code, run it and play with it. However, I do think this part is not essential to explain the approach that I took. The real life solution would require a bit smarter solution possibly a separate draft schema (the approach used on BitQ&A), "forward" revisions or something similar. This comes with some drawbacks changes will be immediately seen to everyone and we will run into issues in case of failed validations. In order to keep things simple we will save changes into the original schema. This article will describe a simplified version of the solution. I was aware that I will need to make sure that the constant inflow of changes won't kill my backend or the database, but I was curious if I can make it work. The more I thought about the problem the more I was convinced that LiveView is the way to go due to its speed and efficiency. Knowing how complicated this would be to achieve in tools that I used in the past, I decided to bite into this one. I already used LiveView for numerous parts of the site (such as real-time Markdown previews), when a feature request for real-time auto save came in. It was also the first project where I had an opportunity to try LiveView (brilliant tool that brings rich real-time UX to Phoenix). BitQ&A is a Phoenix application that I initially created for the 2nd Bitcoin SV virtual hackathon. In the past weeks I spent quite some time working on BitQ&A my side project that explores possibilities that digital currencies offer.