SpaceRocket |> Blog

Think, Learn, Share

Michael Chavez
Michael Chavez

Add LiveView to Phoenix Application

Posted by Michael Chavez on November 15, 2019

mix.exs

...
      {:phoenix_live_view, "~> 0.3.1"}
...
mix deps.get
mix phx.gen.secret 32

config/dev.exs

config :tags_example, TagsExampleWeb.Endpoint,
  http: [port: 4000],
  live_view: [
    signing_salt: "r3WStmK7IODeBb4C1o+7n4dJdyy/PfXv"
  ],
  ...

config/dev.exs

config :tags_example, TagsExampleWeb.Endpoint,
  live_reload: [
    patterns: [
    ...
      ~r{lib/tags_example_web/live/.*(ex)$}
    ]
  ]

config/config.exs

...
config :phoenix,
  template_engines: [leex: Phoenix.LiveView.Engine]
...

lib/tags_example_web/router.ex

  pipeline :browser do
    ...
    plug :fetch_flash
    plug Phoenix.LiveView.Flash
    ...
  end

lib/tags_example_web.ex

...
  def view do
    quote do
      ...
      import Phoenix.LiveView, only: [live_render: 2, live_render: 3]
    end
  end

  def router do
    quote do
      ...
      import Phoenix.LiveView.Router
    end
  end
...

lib/tags_example_web/endpoint.ex

...
  socket "/live", Phoenix.LiveView.Socket
...

assets/package.json

  "dependencies": {
    ...
    "phoenix_live_view": "file:../deps/phoenix_live_view"
  }
npm install --prefix assets &&  npm audit fix --prefix assets

assets/js/app.js

...

import "phoenix_html"
import LiveSocket from "phoenix_live_view"
import {Socket} from "phoenix"

let liveSocket = new LiveSocket("/live", Socket, {})
liveSocket.connect()

lib/tags_example_web/controllers/post_controller.ex

  alias Phoenix.LiveView
  alias TagsExampleWeb.PostLive.New

  def new(conn, _params) do
    LiveView.Controller.live_render(conn, New, session: %{})
  end

lib/tags_example_web/live/post_live/new.ex

defmodule TagsExampleWeb.PostLive.New do
  use Phoenix.LiveView
  alias TagsExample.PostTypes
  alias TagsExample.PostTypes.Post
  alias TagsExampleWeb.PostView

  def mount(_session, socket) do
    # changeset = PostTypes.change_post(%Post{})
    changeset = PostTypes.change_post(%Post{})
    {:ok, assign(socket,changeset: changeset)}
  end

  def render(assigns) do
    PostView.render("new.html", assigns)
  end
end

lib/tags_example_web/templates/post/new.html.leex

<h1>New Post</h1>

<%= render "form.html", Map.put(assigns, :action, Routes.post_path(@socket, :create)) %>

<span><%= link "Back", to: Routes.post_path(@socket, :index) %></span>

Reference: https://elixircasts.io/phoenix-liveview-part-1