The Product Index (Part-I)

Let's learn how state management is done using mount/render in Phoenix LiveView.

How to mount and render the Product index

The mount/render workflow describes the process in which a LiveView sets its initial state and renders it, along with some markup, for the client. The best way to understand the mount/render workflow is to see it in action. The Product Index feature is our entry point into this workflow. We’ll play around with adding specific data to that LiveView’s socket in order to tweak what’s rendered.

The easiest way to put data into the socket is via the mount/3 function. Look at the LiveView’s mount/3 function which is written in pento/lib/pento_web/live/product_live/index.ex:

Press + to interact
def mount(_params, _session, socket) do
{:ok, assign(socket, :products, list_products())}
end
## ...
defp list_products do
Catalog.list_products()
end

The generator has built us a mount/3 function in which the socket assigns is updated with a key of :products, which points a value of all of the products returned from the list_products/0 helper function.

We need to update this mount/3 function to add an additional key of :greeting to the socket assigns. We’ll do so by building a small ...