From a Phoenix LiveView with phx.gen.live, to LiveComponents

From a Phoenix LiveView with phx.gen.live, to LiveComponents

07 December, 2023 2 min read
elixir, phoenix, liveview, webdev

With the help of ChatGPT 3.5, the documentation of Elixir/Phoenix, and lots of IO.inspect and trial-and-error, I finally figured out the basics of how a Phoenix LiveComponent works in combination with a LiveView.

Starting from the basic scaffolding that phx.gen.live created, I ripped out the helper functional component(s) that rendered a list of items in a table, and refactored every list item (a Linux kernel ChangeLog) into its own LiveComponent.

Each such LiveComponent thus has handle_event functions to deal with clicks on its buttons, such as to handle the “process” click that splits a ChangeLog into separate commits and persists them in an SQLite database through Ecto.

As soon as something changes, the parent LiveView only re-renders the LiveComponent from which the change came.

And, based on the state of entity being rendered (here, a ChangeLog), the render function of the LiveComponent shows different buttons leading to different actions, such as “wipe” to keep the ChangeLog and wipe all its related Commits,

I kept the handle_event of “delete” (to delete the ChangeLog entirely) on the LiveView, however, to benefit from stream_delete, when the collection of ChangeLogs will get bigger.

I will need to change the sync changelog-to-commits processing into async processing, because some ChangeLogs are 15+ MB large with thousands of commits, and thus the websocket could time-out while waiting for the processing to finish.

The web app will be deployed on a potato-grade server with an anemic AMD E2-9000e 6W-TDP APU that doesn’t even break the 1000 CPU Mark score , so this is a neat little project for me to learn a lot.

Rows are LiveComponents