Simple Phoenix LiveView App: Upgrade LiveView to v0.8.1

This is episode #9 of a Phoenix LiveView series.

This time we're upgrading LiveView from version 0.5.1 to 0.8.1, and getting both the main app and the throwaway /foo route working again.

Upgrading libraries

We'll start by updating our mix.exs file with the following two changes to our deps:

defp deps do
  [
    {:phoenix, "~> 1.4.15"},
    #...
    {:phoenix_live_view, "~> 0.8.1"}
  ]
end

Fix errors

After upgrading our dependencies, running mix phx.deps.get (or mix at all) throws some errors. That's because our app is calling functions in LiveView that have been moved, renamed or no longer exists. Here's a short summary of what breaks in our app:

  • live_link: We'll need to update our templates to change live_link to live_redirect or live_patch. For links to another page of the same type, e.g. a "next article" link, we can use live_patch. For links to a different type of page powered by a different live view, e.g. a "back to index" link on a show page, we need to use live_redirect.
  • mount: The mount/2 function in our live views must be changed to mount/3. The new parameter, params is the parameters coming in from the router. To update an old mount/2, just add a _params parameter before the other two.
  • redirect: The redirect functions in our live views must be changed to either push_patch, if they're to another page supported by the same live view or to push_redirect if they're to a different page.
  • When doing redirects in our live views, we now return a tuple instead of a tuple.
  • Phoenix.LiveView.Flash: Replace both this plug and fetch_flash with a fetch_live_flash plug in router pipelines. It should be available in the router since Phoenix.LiveView.Router is imported into the Router in web.ex
  • phx-target: The phx-target syntax longer exists, so replace phx-keydown="myevent" phx-target="window" with phx-window-keydown="myevent". Choose a name other than the name of an existing event like "keydown".

Update the error_tag helper

In reactor_web/views/error_helpers.ex, change

  def error_tag(form, field) do
    Enum.map(Keyword.get_values(form.errors, field), fn error ->
      content_tag(:span, translate_error(error), class: "help-block")
    end)
  end

to

  def error_tag(form, field) do
    Enum.map(Keyword.get_values(form.errors, field), fn error ->
      content_tag(:span, translate_error(error),
        class: "help-block",
        data: [phx_error_for: field_id(form, field)]
      )
    end)
  end

With the phx_error_for data attributes, our form validations will now only be triggered for the specific fields being edited instead of running validating the entire form once the first field is completed.

(Source code available for premium members)

Back to index

No Comments