On the Utility of Phoenix LiveView
In order to encourage myself to write a bit more, I’ve rewritten my personal website as a Phoenix-backed blog engine. I love GitHub Pages for a lot of use cases, but I have future plans for this site that will require an API. Additionally, I like to be able to make instant changes without having to write a Git commit message, do a push, and wait for a build pipeline to kick off. As a part of this rewrite, I decided that I wanted the ability to create and edit blog posts within the site. I generally also enjoy writing in Notion and other Markdown editors, but for blogging, I prefer to be able to just write and publish to the same place (all of this may change if Notion ever allows me to have a custom domain for a workspace).
The posts for this blog are written and stored in a database in Markdown. I have an administrator interface that includes a simple plain text editor, and as I was building it, I realized that it would be nice to have a live side-by-side rendering of my post content as I was writing Markdown. Typically, in order to do this, I would have to do one of a couple of different things:
- Wire up my own implementation of a live preview using WebSockets, where I observe change events in the post form, send post content, over a socket, render the Markdown and send HTML back over the socket, then display that rendered Markdown alongside the editor view.
Neither of these sound particularly good to me—after all, running a blog isn’t my day job.
Phoenix LiveView, on the other hand, presents another option. With it, I can move my editing template from a normal Phoenix
*.html.eex template into a LiveView module. The template contents remain basically the same, other than that I now also render a preview of my post contents alongside my editing form, using the same Markdown rendering function used in the view that publicly renders posts.
In order to ensure that live updating happens, I simply add a
phx-change="updated" attribute to my HTML
What I’m most excited for with Phoenix LiveView isn’t necessarily the cool technology that it really is, but more the freedom that it gives me to quickly implement nice-to-have features that would otherwise be too much work to bother with.