Programming Phoenix LiveView B9.0: Generated code uses streams in LiveView 0.19.x so example code no longer works (p. 94)

Since LiveView now supports Streams, the generated code seems to be pushing the user in that direction as well.

As a result, the example code starting on page 94 (in the “Mount and Render the Product Index” section) no longer matches the code created when I run the generator.

It’s not difficult to work around, but the section should definitely be updated to match the new generator code IMO.

This code from the book:

def mount(_params, _session, socket) do
  {:ok, assign(socket, :products, list_products())}
end

# ...

defp list_products do
  Catalog.list_products()
end

Looks more like this in my generated code:

@impl true
def mount(_params, _session, socket) do
  {:ok, stream(socket, :products, Catalog.list_products())}
end

# ...

defp apply_action(socket, :index, _params) do
  socket
  |> assign(:page_title, "Listing Products")
  |> assign(:product, nil)
end

This code from the book showing how to add data to the socket becomes a little confusing as a result:

def mount(_params, _session, socket) do
  {:ok,
    socket
    |> assign(:greeting, "Welcome to Pento!") # add this line
    |> assign(:products, list_products())}
  end

I ended up doing this instead:

@impl true
def mount(_params, _session, socket) do
  socket = assign(socket, :greeting, "Welcome to Pento!")
  {:ok, stream(socket, :products, Catalog.list_products())}
end

Similar outdated function references occur on page 96.

1 Like

You could probably write the mount like this as well, seems a little more clear to me:

@impl true
def mount(_params, _session, socket) do
  {:ok,
    socket
    |> assign(:greeting, “Welcome to Pento!”)
    |> stream(:products, Catalog.list_products())
  }
end

@justinbkay That is definitely a much prettier implementation than what I wrote :+1:

Indeed streams will be addressed and used here in the new Beta book version we’re hard at work on right now. Everything will be updated to use the latest LiveView version and functionality.

1 Like