Skip to content

🤯 beginners tutorial building a real time counter in Phoenix 1.4.16 + LiveView 0.10 ⚡️

License

Notifications You must be signed in to change notification settings

ivymarkwell/phoenix-liveview-counter-tutorial

 
 

Repository files navigation

Phoenix LiveView Counter Tutorial

Build Status codecov.io Hex pm contributions welcome HitCount

Build your first App using Phoenix LiveView and understand all the basic concepts in 20 minutes or less!


Why? 🤷

There are several example apps on GitHub using Phoenix LiveView but none include are step-by-step instructions a complete beginner can follow. This repository is the complete beginner's tutorial we wish we had when learning LiveView and the one you have been looking for!

What? 💭

A complete beginners tutorial for building the most basic possible Phoenix LiveView App with no prior experience necessary.

LiveView?

Phoenix LiveView allows you to build rich interactive web apps with realtime reactive UI (no page refresh when data updates) without having to write any JavaScript! This allows developers to build incredible user experiences with considerably less code.

LiveView pages load instantly because they are rendered on the Server and they require considerably less bandwidth than a similar React, Vue.js, Angular, etc. because only the bare minimum is loaded on the client for the page to work.

See: https://github.com/phoenixframework/phoenix_live_view


Who? 👤

This tutorial is aimed at people who have never built anything in Phoenix or LiveView.

If you get stuck at any point while following the tutorial or you have any feedback/questions, please open an issue on GitHub!

If you don't have a lot of time or bandwidth to watch videos, this tutorial will be the fastest way to learn LiveView.


Prerequisites: What you Need Before You Start 📝

Before you start working through the tutorial, you will need:

a. Elixir installed on your computer. See: learn-elixir#installation

When you run the command:

elixir -v

You should expect to see output similar to the following:

Elixir 1.10.2 (compiled with Erlang/OTP 22)

This informs us we are using Elixir version 1.10.2 which is the latest version at the time of writing.

b. Phoenix installed on your computer. see: hexdocs.pm/phoenix/installation.html

If you run the following command in your terminal:

mix phx.new -v

You should see:

Phoenix v1.4.16

If you have a later version of Phoenix, and you get stuck at any point, please open an issue on GitHub! We are here to help!

c. Node.js installed on your computer. Download it from: https://nodejs.org

If you run the following command in your terminal:

node -v

You should see output similar to:

v12.16.1

Phoenix LiveView does not require the latest Node.js, so if you have a recent version e.g v10, you will be fine.

d. Familiarity with basic Elixir syntax is recommended but not essential;
you can pick it up as you go and ask questions if you get stuck! See: https://github.com/dwyl/learn-elixir


How? 💻

This tutorial takes you through all the steps to build and test a counter in Phoenix LiveView.
We always "begin with the end in mind" so we recommend running the finished app on your machine before writing any code.

💡 You can also try the version deployed to Heroku: https://live-view-counter.herokuapp.com


Step 0: Run the Finished Counter App on your localhost 🏃‍

Before you attempt to build the counter, we suggest that you clone and run the complete app on your localhost.
That way you know it's working without much effort/time expended.

Clone the Repository

On your localhost, run the following command to clone the repo and change into the directory:

git clone https://github.com/dwyl/phoenix-liveview-counter-tutorial.git
cd phoenix-liveview-counter-tutorial

Download the Dependencies

Install the Elixir dependencies by running the command:

mix deps.get

Install the Node.js dependencies with:

npm install --prefix assets
# or `cd assets && npm install && cd ..` for Windows users if --prefix doesn't work

It will take a few seconds to download the dependencies depending on the speed of your internet connection; be patient. 😉

Run the App

Start the Phoenix server by running the command:

mix phx.server

Now you can visit localhost:4000 in your web browser.

💡 Open a second browser window (e.g. incognito mode), you will see the the counter updating in both places like magic!

You should expect to see:

phoenix-liveview-counter-start

With the finished version of the App running on your machine and a clear picture of where we are headed, it's time to build it!


Step 1: Create the App 🆕

In your terminal run the following mix command to generate the new Phoenix app:

mix phx.new live_view_counter --no-ecto

The --no-ecto flag tells mix phx.new to create an App without a Database.
This keeps our counter as simple as possible. We can always add a Database to store the counter later.

When you see the following prompt:

Fetch and install dependencies? [Yn]

Type Y followed by the [Enter] key. That will download all the necessary dependencies.


Checkpoint 1: Run the Tests!

In your terminal, run the following mix command:

mix test

You should see:

Generated phoenix app
==> live_view_counter
Compiling 14 files (.ex)
Generated live_view_counter app
...

Finished in 0.02 seconds
3 tests, 0 failures

Tests all pass. This is expected with a new app. It's a good way to confirm everything is working.


Checkpoint 1b: Run the New Phoenix App!

Run the server by executing this command:

mix phx.server

Visit localhost:4000 in your web browser.

welcome-to-phoenix

🏁 Snapshot of code at the end of Step 1: phoenix-liveview-counter-tutorial/pull/4/commits/0d94a1c


Step 2: Add LiveView to deps in mix.exs File

Now that we have a working basic Phoenix App, it's time to setup phoenix_live_view to work with our App. There are quite a few steps but they only take a couple of minutes to complete; don't be put off by the configuration, the payoff is worth it!

💡 This tutorial follows and expands on the official Phoenix LiveView installation instructions: github.com/phoenixframework/phoenix_live_view/blob/master/guides/introduction/installation.md
We always prefer more detailed instructions when learning so we have added more detail to each step. Crucially we know all the steps in this tutorial work flawlessly, because the counter works in the finished example. If you followed the instructions in "Step 0" to run the finished app on your localhost before diving into building it, you also know they work for you. ✅

Open the mix.exs file and locate the deps list, e.g:

defp deps do
  [
    {:phoenix, "~> 1.4.16"},
    {:phoenix_pubsub, "~> 1.1"},
    {:phoenix_html, "~> 2.11"},
    {:phoenix_live_reload, "~> 1.2", only: :dev},
    {:gettext, "~> 0.11"},
    {:jason, "~> 1.0"},
    {:plug_cowboy, "~> 2.0"}
  ]
end

Append the following line to the end of the list:

{:phoenix_live_view, "~> 0.10.0"},

The deps definition should now look likes this:

defp deps do
  [
    {:phoenix, "~> 1.4.16"},
    {:phoenix_pubsub, "~> 1.1"},
    {:phoenix_html, "~> 2.11"},
    {:phoenix_live_reload, "~> 1.2", only: :dev},
    {:gettext, "~> 0.11"},
    {:jason, "~> 1.0"},
    {:plug_cowboy, "~> 2.0"},
    {:phoenix_live_view, "~> 0.10.0"},
  ]
end

The last line in the code block is the important one.

🏁 mix.exs file at the end of Step 2: mix.exs#L44


2.1 Download the phoenix_live_view Dependency

Now that you've added the phoenix_live_view to mix.exs, you need to download the dependencies. Run:

mix deps.get

You should see output similar to:

Resolving Hex dependencies...
Dependency resolution completed:
Unchanged:
  cowboy 2.7.0
  ...
New:
  phoenix_live_view 0.9.0
* Getting phoenix_live_view (Hex package)

Step 3. Configure signing_salt in config.exs

Phoenix LiveView uses a cryptographic salt to secure communications between client and server. 🔐
You don't need to know what this is, just follow the instructions below and you'll be fine, but if you are curious, read: https://en.wikipedia.org/wiki/Salt_(cryptography)

In your terminal run the following command:

mix phx.gen.secret 32

You should see output similar to the following:

iluKTpVJp8PgtRHYv1LSItNuQ1bLdR7c

💡 This is a random string generator that generates a 32 character string of alphanumeric data,
so the result will be different each time you run the command.

Copy the string into your computer's clipboard.

Open your config/config.exs file and locate the line that begins with live_view:

In this case it is the last line in the "Configures the endpoint" block:

# Configures the endpoint
config :live_view_counter, LiveViewCounterWeb.Endpoint,
  url: [host: "localhost"],
  secret_key_base: "K73oqZVIRIAck+a4sNK0V/hPujAYLeXGrKwax57JXFKMb8z64kgTaMF0Ys/Ikhrm",
  render_errors: [view: LiveViewCounterWeb.ErrorView, accepts: ~w(html json)],
  pubsub: [name: LiveViewCounter.PubSub, adapter: Phoenix.PubSub.PG2],
  live_view: [signing_salt: "dUvMl2Sn"]

Replace the String value for signing_salt with the one you generated in your terminal:

# Configures the endpoint
config :live_view_counter, LiveViewCounterWeb.Endpoint,
  url: [host: "localhost"],
  secret_key_base: "K73oqZVIRIAck+a4sNK0V/hPujAYLeXGrKwax57JXFKMb8z64kgTaMF0Ys/Ikhrm",
  render_errors: [view: LiveViewCounterWeb.ErrorView, accepts: ~w(html json)],
  pubsub: [name: LiveViewCounter.PubSub, adapter: Phoenix.PubSub.PG2],
  live_view: [signing_salt: "iluKTpVJp8PgtRHYv1LSItNuQ1bLdR7c"]

The last line in the code block is the important one.

🏁 At the end of Step 3 the config.exs file should look like this: config/config.exs#L16

💡Note: in a real world App, we would use an environment variable for the signing_salt to ensure it is kept secret.

If your the config in your config.exs file does not have a live_view: line, create a new config block at the end of your file:

config :live_view_counter, LiveViewCounterWeb.Endpoint,
   live_view: [
     signing_salt: "iluKTpVJp8PgtRHYv1LSItNuQ1bLdR7c"
   ]

Step 4: Add Phoenix.LiveView Helpers to live_view_counter_web.ex

Open the lib/live_view_counter_web.ex file and add the relevant Phoenix.LiveView import statements for each of the controller, view and router blocks.

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

def view do
  quote do
    ...
+   import Phoenix.LiveView.Helpers
  end
end

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

🏁 Changes made in Step 4:
Before: lib/live_view_counter_web.ex
After: lib/live_view_counter_web.ex#L27 The relevant lines are 27, 46 and 55.


Step 5: Add :fetch_live_flash Plug to Browser Pipeline

Replace the regular Phoenix flash plug with the LiveView flash plug.

Open the lib/live_view_counter_web/router.ex file and locate the pipeline :browser do block. e.g:

pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_flash
  plug :protect_from_forgery
  plug :put_secure_browser_headers
end

Replace the line plug :fetch_flash with plug :fetch_live_flash such that it now looks like this:

pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_live_flash
  plug :protect_from_forgery
  plug :put_secure_browser_headers
end

That ensures flash messages (e.g: "not connected to network") are displayed in the client when the LiveView App is running.

🏁 At the end of Step 5, the lib/live_view_counter_web/router.ex should look like: router.ex#L8


Step 6: Create the /live Socket in endpoint.ex

In order to allow the client(s) to communicate with the server, we need to open a socket. Open the lib/live_view_counter_web/endpoint.ex file and locate the plug Plug.Session block:

plug Plug.Session
  store: :cookie,
  key: "_my_app_key",
  signing_salt: "somesigningsalt"

Replace it with the following @session_options module attribute at the top of the file and reference @session_options in the plug configuration:

@session_options [
  store: :cookie,
  key: "_my_app_key",
  signing_salt: "iluKTpVJp8PgtRHYv1LSItNuQ1bLdR7c"
]

plug Plug.Session, @session_options

see: endpoint.ex#L7-L11 and endpoint.ex#L48

Next add the following lines to the endpoint.ex:

socket "/live", Phoenix.LiveView.Socket,
  websocket: [connect_info: [session: @session_options]]

This exposes a socket in the /live namespace for the LiveView updates.

🏁 Changes made in Step 6: lib/live_view_counter_web/endpoint.ex#L13-L14


Step 7: Add phoenix_live_view to Node.js Dependencies in package.json

In order for the LiveView client to work in the web browser, we need to add the LiveView NPM dependency to the dependencies in the assets/package.json file.

Locate the "dependencies" section:

"dependencies": {
  "phoenix": "file:../deps/phoenix",
  "phoenix_html": "file:../deps/phoenix_html"
},

Add the line: "phoenix_live_view": "file:../deps/phoenix_live_view" so that it now looks like this:

"dependencies": {
  "phoenix": "file:../deps/phoenix",
  "phoenix_html": "file:../deps/phoenix_html",
  "phoenix_live_view": "file:../deps/phoenix_live_view"
}

🏁 Changes made in Step 7: assets/package.json#L11


7.1 Install the NPM Dependency

Once you've added the line to the package.json file, you will need to run the following command to install the dependency:

npm install --prefix assets
# or `cd assets && npm install && cd ..` for Windows users if --prefix doesn't work

You should expect to see output similar to the following:

added 1 package from 1 contributor and audited 8438 packages in 4.257s

Step 8: Rename Layout Template File from app.html.eex to app.html.leex

In order to render the layout template as a "live" view, we need to rename it. In your project, locate the lib/live_view_counter_web/templates/layout/app.html.eex file and rename it to: app.html.leex (we just changed the extension from .eex to leex which stands for "liveview embedded elixir" template).

Once you have renamed the file, replace the contents of the file with the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title><%= assigns[:page_title] || "LiveViewCounter · Phoenix Framework" %></title>
    <link rel="stylesheet" href="<%= Routes.static_path(@socket, "/css/app.css") %>"/>
    <%= csrf_meta_tag() %>
  </head>
  <body>
    <header>
      <section class="container">
        <a href="https://phoenixframework.org/" class="phx-logo">
          <img src="<%= Routes.static_path(@socket, "/images/phoenix.png") %>" alt="Phoenix Framework Logo"/>
        </a>
      </section>
    </header>
    <main role="main" class="container">
      <p class="alert alert-info" role="alert"><%= live_flash(@flash, :notice) %></p>
      <p class="alert alert-danger" role="alert"><%= live_flash(@flash, :error) %></p>
      <%= @inner_content %>
    </main>
    <%= csrf_meta_tag() %>
    <script type="text/javascript" src="<%= Routes.static_path(@socket, "/js/app.js") %>"></script>
  </body>
</html>

🏁 For the full side-by-side view of the changes made in this step, see: commit/031e034


Summary of Code Changes made to app.html.leex Template

  • replace all instances of @conn with @socket.
  • replace get_flash(@conn with live_flash(@flash
  • replace render @view_module, @view_template, assigns with @inner_content

Step 9: Add LiveView code to app.js

In order for the client to connect to LiveView, we need to add some lines of code to app.js.
Open the assets/js/app.js file and add the lines:

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

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}});
liveSocket.connect()

🏁 Code added in Step 9: assets/js/app.js#L19-L24


Step 10: Import the live_view.css in app.css

In order to display the "connecting" and "offline" UI in our counter, we need to import the live_view.css file in our app.css.

Open the assets/css/app.css file and append the following line:

@import "../../deps/phoenix_live_view/assets/css/live_view.css";

🏁 The line of code added in Step 10 is: /assets/css/app.css#L4


We are finally finished setting up our Counter App to use LiveView! Now we get to the fun part: creating the counter!! 🎉


Step 11: Create the counter.ex File

In the lib/live_view_counter_web directory, create a new directory called live:

mkdir lib/live_view_counter_web/live

Then create a new file with the path: lib/live_view_counter_web/live/counter.ex

And add the following code to it:

defmodule LiveViewCounterWeb.Counter do
  use Phoenix.LiveView

  def mount(_params, _session, socket) do
    {:ok, assign(socket, :val, 0),
      layout: {LiveViewCounterWeb.LayoutView, "app.html"}}
  end

  def handle_event("inc", _, socket) do
    {:noreply, update(socket, :val, &(&1 + 1))}
  end

  def handle_event("dec", _, socket) do
    {:noreply, update(socket, :val, &(&1 - 1))}
  end

  def render(assigns) do
    ~L"""
    <div>
      <h1>The count is: <%= @val %></h1>
      <button phx-click="dec">-</button>
      <button phx-click="inc">+</button>
    </div>
    """
  end
end

Explanation of the Code

The first line instructs Phoenix to use the Phoenix.LiveView behaviour. This loads just means that we will need to implement certain functions for our live view to work.

The first function is mount/3 which, as it's name suggests, mounts the module with the _params, _session and socket arguments:

def mount(_params, _session, socket) do
  {:ok, assign(socket, :val, 0)
    layout: {LiveViewCounterWeb.LayoutView, "app.html"} }
end

In our case we are ignoring the _params and _session, hence the underscore prepended to the parameters. If we were using sessions user management, we would need to check the session variable, but in this simple counter example we just ignore it.

mount/3 returns a tuple: {:ok, assign(socket, :val, 0)} which uses the assign/3 function to assign the :val key a value of 0 on the socket. That just means the socket will now have a :val which is initialised to 0. Specifying the layout template as app.html is needed for Phoenix LiveView to know which template file to use.


The second function is handle_event/3 which handles the incoming events received. In the case of the first declaration of handle_event("inc", _, socket) it pattern matches the string "inc" and increments the counter.

def handle_event("inc", _, socket) do
  {:noreply, update(socket, :val, &(&1 + 1))}
end

handle_event/3 ("inc") returns a tuple of: {:noreply, update(socket, :val, &(&1 + 1))} where the :noreply just means "do not send any further messages to the caller of this function". update(socket, :val, &(&1 + 1)) as it's name suggests, will update the value of :val on the socket to the &(&1 + 1) is a shorthand way of writing fn val -> val + 1 end. the &() is the same as fn ... end (where the ... is the function definition). If this inline anonymous function syntax is unfamiliar to you, please read: https://elixir-lang.org/crash-course.html#partials-and-function-captures-in-elixir

The third function is almost identical to the one above, the key difference is that it decrements the :val.

def handle_event("dec", _, socket) do
  {:noreply, update(socket, :val, &(&1 - 1))}
end

handle_event("dec", _, socket) pattern matches the "dec" String and decrements the counter using the &(&1 - 1) syntax.

In Elixir we can have multiple similar functions with the same function name but different matches on the arguments or different "arity" (number of arguments).
For more detail on Functions in Elixir, see: https://elixirschool.com/en/lessons/basics/functions/#named-functions

Finally the third function render/1 receives the assigns argument which contains the :val state and renders the template using the @val template variable.

The render/1 function renders the template included in the function. The ~L""" syntax just means "treat this multiline string as a LiveView template" The ~L sigil is a macro included when the use Phoenix.LiveView is invoked at the top of the file.

LiveView will invoke the mount/3 function and will pass the result of mount/3 to render/1 behind the scenes.

Each time an update happens (e.g: handle_event/3) the render/1 function will be executed and updated data (in our case the :val count) is sent to the client.

🏁 At the end of Step 11 you should have a file similar to: lib/live_view_counter_web/live/counter.ex


Step 12: Create the live Route in router.ex

Now that we have created our Live handler function in Step 11, it's time to tell Phoenix how to invoke it.

Open the lib/live_view_counter_web/router.ex file and locate the block of code that starts with scope "/", LiveViewCounterWeb do:

scope "/", LiveViewCounterWeb do
  pipe_through :browser

  get "/", PageController, :index
end

Replace the line get "/", PageController, :index with live("/", Counter). So you end up with:

scope "/", LiveViewCounterWeb do
  pipe_through :browser

  live("/", Counter)
end

🏁 At the end of Step 12 you should have a router.ex file similar to: lib/live_view_counter_web/router.ex#L20


12.1 Update the Failing Test Assertion

Since we have replaced the get "/", PageController, :index route in router.ex in the previous step, the test in test/live_view_counter_web/controllers/page_controller_test.exs will now fail:

Compiling 1 file (.ex)
..

  1) test GET / (LiveViewCounterWeb.PageControllerTest)
     test/live_view_counter_web/controllers/page_controller_test.exs:4
     Assertion with =~ failed
     code:  assert html_response(conn, 200) =~ "Welcome to Phoenix!"
     left:  "<!DOCTYPE html>\n<html lang=\"en\">\n  
     <head>\n <meta charset=\"utf-8\"/>\n
     <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"/>\n
     <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n
     <title>LiveViewCounter · Phoenix Framework</title>\n  
     </head>\n  <body>\n <header>\n <section class=\"container\">\n
     <a href=\"https://phoenixframework.org/\" class=\"phx-logo\">\n
     <img src=\"/images/phoenix.png\" alt=\"Phoenix Framework Logo\"/>\n </a>\n
     </section>\n </header>\n <main role=\"main\" class=\"container\">\n
     <div data-phx-main=\"true\"
     <h1>The count is: 0</h1>\n  <button phx-click=\"dec\">-</button>\n  
     <button phx-click=\"inc\">+</button>\n</div>\n</div>    
     </main> <script type=\"text/javascript\" src=\"/js/app.js\"></script>\n  
     </body>\n</html>\n"
     right: "Welcome to Phoenix!"
     stacktrace:
       test/live_view_counter_web/controllers/page_controller_test.exs:6: (test)

Finished in 0.1 seconds
3 tests, 1 failure

This just tells us that the test is looking for the string "Welcome to Phoenix!" in the page and did not find it.

To fix the broken test, open the test/live_view_counter_web/controllers/page_controller_test.exs file and locate the line:

assert html_response(conn, 200) =~ "Welcome to Phoenix!"

Update the string from "Welcome to Phoenix!" to something we know is present on the page, e.g: "The count is"

🏁 The page_controller_test.exs file should now look like this: test/live_view_counter_web/controllers/page_controller_test.exs#L6

Confirm the tests pass again by running:

mix test

You should see output similar to:

Generated live_view_counter app
...

Finished in 0.05 seconds
3 tests, 0 failures

Checkpoint: Run Counter App!

Now that all the code for the counter.ex is written, run the Phoenix app with the following command:

mix phx.server

Vist localhost:4000 in your web browser.

You should expect to see a fully functioning LiveView counter:

phoenix-liveview-counter-single-windowl


Recap: Working Counter Without a JavaScript Framework

Once the initial installation and configuration of LiveView (Steps 1 - 10 of this tutorial) were complete, the creation of the actual counter was remarkably simple. We created a single new file lib/live_view_counter_web/live/counter.ex that contains all the code required to initialise, render and update the counter. Then we set the live("/", Counter) route to invoke the Counter module in router.ex.

In total our counter App is 25 lines of code.


One important thing to note is that the counter only maintains state for a single web browser. Try opening a second browser window (e.g: in "incognito mode") and notice how the counter only updates in one window at a time:

phoenix-liveview-counter-two-windows-independent-count

If we want to share the counter state between multiple clients, we need to add a bit more code.


Step 13: Share State Between Clients!

One of the biggest selling points of using Phoenix to build web apps is the built-in support for WebSockets in the form of "channels". Phoenix Channels allow us to effortlessly sync data between clients and servers with minimal overhead.

We can share the counter state between multiple clients by updating the counter.ex file with the following code:

defmodule LiveViewCounterWeb.Counter do
  use Phoenix.LiveView

  @topic "live"

  def mount(_session, _params, socket) do
    LiveViewCounterWeb.Endpoint.subscribe(@topic) # subscribe to the channel
    {:ok, assign(socket, :val, 0),
      layout: {LiveViewCounterWeb.LayoutView, "app.html"}}
  end

  def handle_event("inc", _value, socket) do
    new_state = update(socket, :val, &(&1 + 1))
    LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "inc", new_state.assigns)
    {:noreply, new_state}
  end

  def handle_event("dec", _, socket) do
    new_state = update(socket, :val, &(&1 - 1))
    LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "dec", new_state.assigns)
    {:noreply, new_state}
  end

  def handle_info(msg, socket) do
    {:noreply, assign(socket, val: msg.payload.val)}
  end

  def render(assigns) do
    ~L"""
    <div>
      <h1>The count is: <%= @val %></h1>
      <button phx-click="dec">-</button>
      <button phx-click="inc">+</button>
    </div>
    """
  end
end

Code Explanation

The first change is on Line 4 @topic "live" defines a module attribute (think of it as a global constant), that lets us to reference @topic anywhere in the file.

The second change is on Line 7 where the mount/3 function now creates a subscription to the topic:

LiveViewCounterWeb.Endpoint.subscribe(@topic) # subscribe to the channel topic

Each client connected to the App subscribes to @topic so when the count is updated on any of the clients, all the other clients see the same value. This uses Phoenix's built-in channels (WebSocket) system.

Next we update the first handle_event/3 function which handles the "inc" event:

def handle_event("inc", _msg, socket) do
  new_state = update(socket, :val, &(&1 + 1))
  LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "inc", new_state.assigns)
  {:noreply, new_state}
end

Assign the result of the update invocation to new_state so that we can use it on the next two lines. Invoking LiveViewCounterWeb.Endpoint.broadcast_from sends a message from the current process self() on the @topic, the key is "inc" and the value is the new_state.assigns Map.

In case you are curious (like we are), new_state is an instance of the Phoenix.LiveView.Socket socket:

#Phoenix.LiveView.Socket<
  assigns: %{
    flash: %{},
    live_view_action: nil,
    live_view_module: LiveViewCounterWeb.Counter,
    val: 1
  },
  changed: %{val: true},
  endpoint: LiveViewCounterWeb.Endpoint,
  id: "phx-Ffq41_T8jTC_3gED",
  parent_pid: nil,
  view: LiveViewCounterWeb.Counter,
  ...
}

The new_state.assigns is a Map that includes the key val where the value is 1 (after we clicked on the increment button).

The fourth update is to the "dec" version of handle_event/3

def handle_event("dec", _msg, socket) do
  new_state = update(socket, :val, &(&1 - 1))
  LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "dec", new_state.assigns)
  {:noreply, new_state}
end

The only difference from the "inc" version is the &(&1 - 1) and "dec" in the broadcast_from.

The final change is the implementation of the handle_info/2 function:

def handle_info(msg, socket) do
  {:noreply, assign(socket, msg.payload)}
end

handle_info/2 handles Elixir process messages where msg is the received message and socket is the Phoenix.Socket.
The line {:noreply, assign(socket, msg.payload)} just means "don't send this message to the socket again" (which would cause a recursive loop of updates).

🏁 The changes made in Step 13 are: lib/live_view_counter_web/live/counter.ex


Checkpoint: Run It!

Now that counter.ex has been update to broadcast the count to all connected clients, let's run the app in a few web browsers to show it in action!

In your terminal, run:

mix phx.server

Open localhost:4000 in as many web browsers as you have and test the increment/decrement buttons!

You should see the count increasing/decreasing in all browsers simultaneously!

phoenix-liveview-counter-four-windows


Congratulations! 🎉

You just built a real-time counter that seamlessly updates all connected clients using Phoenix LiveView in less than 40 lines of code!


Step 14: Use a LiveView Template (Optional)

At present the render/1 function in counter.ex has an inline template:

def render(assigns) do
  ~L"""
  <div>
    <h1>The count is: <%= @val %></h1>
    <button phx-click="dec">-</button>
    <button phx-click="inc">+</button>
  </div>
  """

This is fine when the template is small like in this counter, but it's a good idea to split the template into a separate file to make it easier to read and maintain.

Create a new file called counter.html.leex in the lib/live_view_counter_web/templates/page/ directory and add the following code to it:

<div>
  <h1>The count is: <%= @val %></h1>
  <button phx-click="dec">-</button>
  <button phx-click="inc">+</button>
</div>

🏁 Your counter.html.leex should look like this: lib/live_view_counter_web/templates/page/counter.html.leex

That template is identical to the one we had in the render/1 function; that's the point: we just want it in a separate file.


Now open the counter.ex file and locate the render/1 function. Update the code to:

def render(assigns) do
  LiveViewCounterWeb.PageView.render("counter.html", assigns)
end

🏁 At the end of Step 14 your counter.ex file should resemble: lib/live_view_counter_web/live/counter.ex

Re-run your app using mix phx.server and confirm everything still works:

phoenix-liveview-counter-42



Done!

That's it for this tutorial.
We hope you enjoyed learning with us!
If you found this useful, please ⭐️and share the GitHub repo so we know you like it!




Credits & Thanks! 🙌

Credit for inspiring this tutorial goes to Dennis Beatty @dnsbty for his superb post: https://dennisbeatty.com/2019/03/19/how-to-create-a-counter-with-phoenix-live-view.html and corresponding video: youtu.be/2bipVjOcvdI

dennisbeatty-counter-video

We recommend everyone learning Elixir subscribe to his YouTube channel and watch all his videos as they are a superb resource!

The 3 key differences between this tutorial and Dennis' original post are:

  1. Complete code commit (snapshot) at the end of each section (not just inline snippets of code).
    We feel that having the complete code speeds up learning significantly, especially if (when) we get stuck.
  2. Latest Phoenix, Elixir and LiveView versions. A few updates have been made to LiveView setup, these are reflected in our tutorial which uses the latest release.
  3. Broadcast updates to all connected clients. So when the counter is incremented/decremented in one client, all others see the update. This is the true power and "wow moment" of LiveView!

Phoenix LiveView for Web Developers Who Don't know Elixir

If you are new to LiveView (and have the bandwidth), we recommend watching James @knowthen Moore's intro to LiveView where he explains the concepts: youtu.be/U_Pe8Ru06fM

phoenix-liveview-intro-

Watching the video is not required; you will be able to follow the tutorial without it.


Chris McCord (creator of Phoenix and LiveView) has github.com/chrismccord/phoenix_live_view_example
chris-phoenix-live-view-example-rainbow It's a great collection of examples for people who already understand LiveView. However we feel that it is not very beginner-friendly (at the time of writing). Only the default "start your Phoenix server" instructions are included, and the dependencies have diverged so the app does not compile/run for some people. We understand/love that Chris is focussed building Phoenix and LiveView so we decided to fill in the gaps and write this beginner-focussed tutorial.


If you haven't watched Chris' Keynote from ElixirConf EU 2019, we highly recommend watching it: youtu.be/8xJzHq8ru0M

chris-keynote-elixirconf-eu-2019

Also read the original announcement for LiveView to understand the hype!
: https://dockyard.com/blog/2018/12/12/phoenix-liveview-interactive-real-time-apps-no-need-to-write-javascript


Sophie DeBenedetto's ElixirConf 2019 talk "Beyond LiveView: Building Real-Time features with Phoenix LiveView, PubSub, Presence and Channels (Hooks) is worth watching: youtu.be/AbNAuOQ8wBE

Sophie-DeBenedetto-elixir-conf-2019-talk

Related blog post: https://elixirschool.com/blog/live-view-live-component/

About

🤯 beginners tutorial building a real time counter in Phoenix 1.4.16 + LiveView 0.10 ⚡️

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Elixir 63.0%
  • CSS 25.2%
  • JavaScript 9.4%
  • HTML 2.4%