DEV Community

Cover image for How to Setup Phoenix LiveView
Alvise Susmel
Alvise Susmel

Posted on • Originally published at poeticoding.com on

How to Setup Phoenix LiveView

Understanding Phoenix LiveView

Subscribe to get FREE Tutorials by email. Start learning Elixir and Phoenix to build features and apps!

Phoenix LiveView has been released on Hex! Although it's still not a stable release (at the time of writing 0.3.1), it works really well and it's packed of cool features.

Since the first version, I'm so impressed with how easy and fast I can develop a real-time application with LiveView, without using a complex JavaScript framework.

But to me, the most important LiveView's aspect is the productivity boost! Be able to focus on where data reside and are processed while being sure that changes are pushed to the front-end, updating the UI automatically. It really feels like magic!

In this article we see how to get started with Phoenix LiveView by creating a new Phoenix app and going through the LiveView setup.

In the next articles we’ll see how to use this setup to build a super-simple LiveView application called Gallery, which we’ll use to develop our first LiveView page and understand how LiveView works under the hood.

In this app the user can interact with the LiveView page and go through a gallery of images by clicking the interface buttons.

Gallery app - LiveView

Create a new Phoenix project

Let's first create a new Phoenix project. We need the latest stable Phoenix Framework and Node.js installed.

$ mix phx.new gallery --no-ecto
Enter fullscreen mode Exit fullscreen mode

Since we don't need any database, we use the --no-ecto option. Our gallery will just be a list of image urls.

Now, how can we setup LiveView?
At the moment there are no LiveView generators, so we need to manually integrate it, changing some files and macros.

:phoenix_live_view in mix.exs

Let's start by adding the phoenix_live_view library under the mix.exs dependencies. We can set the release version we find on Hex

defp deps do
[
  {:phoenix, "~> 1.4.10"},
    ...
  {:phoenix_live_view, "~> 0.3.1"}
]
end
Enter fullscreen mode Exit fullscreen mode

or if you prefer to try the latest committed code, you can directly use the GitHub LiveView master branch

defp deps do
[
  {:phoenix, "~> 1.4.10"},
    ...
  {:phoenix_live_view, github: "phoenixframework/phoenix_live_view"}
]
end
Enter fullscreen mode Exit fullscreen mode

In our case we set the 0.3.1 version and get the dependencies running mix deps.get in the terminal

$ mix deps.get
...
New:
  phoenix_live_view 0.3.1
* Getting phoenix_live_view (Hex package)
Enter fullscreen mode Exit fullscreen mode

Signing salt in config/config.exs

Now we need to update the endpoint configuration in config/config.exs, adding the LiveView signing salt.

To generate a new salt we use the mix task

$ mix phx.gen.secret 32
LIlgBfJ9j7xLJ6Almy982/ZydK/9y0vd
Enter fullscreen mode Exit fullscreen mode
# config/config.exs

config :gallery, GalleryWeb.Endpoint,
    ...
  live_view: [
    signing_salt: "LIlgBfJ9j7xLJ6Almy982/ZydK/9y0vd"
  ]
Enter fullscreen mode Exit fullscreen mode

LiveView Flash plug

Then, we add the LiveView Flash plug to our :browser pipeline in lib/gallery_web/router.ex, just after :fetch_flash

# lib/gallery_web/router.ex
pipeline :browser do
    ...
    plug :fetch_flash
    plug Phoenix.LiveView.Flash
    ...
end
Enter fullscreen mode Exit fullscreen mode

Imports in lib/gallery_web.ex

We now update the lib/gallery_web.ex web file, adding some imports to the controller, view and router functions

# lib/gallery_web.ex

def controller do
    quote do
        ... 
      import Phoenix.LiveView.Controller
    end
end

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

def router do
  quote do
    ...
    import Phoenix.LiveView.Router
  end
end
Enter fullscreen mode Exit fullscreen mode

Socket in lib/gallery_web/endpoint.ex

Next, we expose a new socket for LiveView updates in the endpoint module lib/gallery_web/endpoint.ex. This socket is used by LiveView to send updates and receive events.

defmodule GalleryWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :gallery

  socket "/live", Phoenix.LiveView.Socket
  ...
end
Enter fullscreen mode Exit fullscreen mode

JavaScript and CSS

Now let's focus on the client side - we need to add the LiveView JavaScript library in assets/package.json.

{
  "dependencies": {
        ...
    "phoenix_live_view": "file:../deps/phoenix_live_view"
  }
}
Enter fullscreen mode Exit fullscreen mode

This library will run on the browser, updating the DOM, managing user events while talking with the LiveView process on the server.

To install the new javascript dependency we've just added, run

$ npm install --prefix assets
Enter fullscreen mode Exit fullscreen mode

We are almost ready, we just need to add four lines of javascript code in assets/js/app.js, which starts LiveView on the client

// assets/js/app.js
import {Socket} from "phoenix"
import LiveSocket from "phoenix_live_view"

let liveSocket = new LiveSocket("/live", Socket)
liveSocket.connect()
Enter fullscreen mode Exit fullscreen mode

and import the default LiveView CSS in assets/css/app.css

/* assets/css/app.css */

@import "../../deps/phoenix_live_view/assets/css/live_view.css";
Enter fullscreen mode Exit fullscreen mode

Done! Let's see if everything works

Great, the setup is finished and LiveView is ready! Let's see now if everything works by creating a super-simple LiveView module that renders some text.

After creating the lib/gallery_web/live directory, we open in it a new file called gallery_live.ex. In this new file we define the GalleryWeb.GalleryLive module (our LiveView page - just copy/paste the code below, we will dig into LiveView functionalities in next articles)

defmodule GalleryWeb.GalleryLive do
  use Phoenix.LiveView

  def mount(_session, socket) do
    {:ok, socket}
  end

  def render(assigns) do
    ~L"""
    <h1>LiveView is awesome!</h1>
    """
  end
end
Enter fullscreen mode Exit fullscreen mode

Inside the render/1 function we have a LiveView template that will show on our browser the message LiveView is awesome!.

Almost there... we just need to add a live route in our router lib/gallery_web/router.ex

# lib/gallery_web/router.ex

defmodule GalleryWeb.Router do
  use GalleryWeb, :router

  ...

  scope "/", GalleryWeb do
    ...

      live "/gallery", GalleryLive  
  end
end
Enter fullscreen mode Exit fullscreen mode

and after running the Phoenix server

$ mix phx.server

[info] Running GalleryWeb.Endpoint with cowboy 2.7.0 at 0.0.0.0:4000 (http)
[info] Access GalleryWeb.Endpoint at http://localhost:4000
...
Enter fullscreen mode Exit fullscreen mode

opening the page http://localhost:4000/gallery we should see our LiveView page.

Working LiveView page

What's next

In the following article, the Primitives of Phoenix LiveView we learn the LiveView basics, exploring the Phoenix LiveView primitives, understanding the magic behind LiveView while learning how we can build a simple counter.

Take also a look at the Phoenix LiveView documentation. It's a great read which gives a solid understanding of how things work and which kind of features are available.

Another great resource is the chrismccord/phoenix_live_view_example GitHub repo, where you find easy code examples showing all the different LiveView's features.

Subscribe to get FREE Tutorials by email. Start learning Elixir and Phoenix to build features and apps!

Top comments (0)