All Projects โ†’ dwyl โ†’ Phoenix Liveview Counter Tutorial

dwyl / Phoenix Liveview Counter Tutorial

Licence: gpl-2.0
๐Ÿคฏ beginners tutorial building a real time counter in Phoenix 1.5.5 + LiveView 0.14.7 โšก๏ธ

Programming Languages

elixir
2628 projects

Projects that are alternatives of or similar to Phoenix Liveview Counter Tutorial

Phoenix Todo List Tutorial
โœ… Complete beginners tutorial building a todo list from scratch in Phoenix 1.5.3 (latest)
Stars: โœญ 65 (-43.48%)
Mutual labels:  phoenix, tutorial, learn, beginner
Phoenix Ecto Append Only Log Example
๐Ÿ“ A step-by-step example/tutorial showing how to build a Phoenix (Elixir) App where all data is immutable (append only). Precursor to Blockchain, IPFS or Solid!
Stars: โœญ 58 (-49.57%)
Mutual labels:  phoenix, tutorial, learn, howto
Javascript Todo List Tutorial
โœ… A step-by-step complete beginner example/tutorial for building a Todo List App (TodoMVC) from scratch in JavaScript following Test Driven Development (TDD) best practice. ๐ŸŒฑ
Stars: โœญ 212 (+84.35%)
Mutual labels:  tutorial, learn, beginner, how-to
Start Here
๐Ÿ’ก A Quick-start Guide for People who want to dwyl โค๏ธ โœ…
Stars: โœญ 1,392 (+1110.43%)
Mutual labels:  learn, beginner, how-to, howto
Phoenix Chat Example
๐Ÿ’ฌ A Step-by-Step Beginners Tutorial for Building, Testing & Deploying a Chat app in Phoenix 1.5.5 ๐Ÿš€
Stars: โœญ 452 (+293.04%)
Mutual labels:  phoenix, tutorial, learn, beginner
Avenging
MVP pattern example on Android: no Dagger or RxJava example
Stars: โœญ 279 (+142.61%)
Mutual labels:  tutorial, example, howto
Llvm 9.0 Learner Tutorial
A blog for LLVM(v9.0.0 or v11.0.0) beginner, step by step, with detailed documents and comments. Record the way I learn LLVM and accomplish a complete project for FPGA High-Level Synthesis with it.
Stars: โœญ 58 (-49.57%)
Mutual labels:  tutorial, learn, beginner
Learn To Send Email Via Google Script Html No Server
๐Ÿ“ง An Example of using an HTML form (e.g: "Contact Us" on a website) to send Email without a Backend Server (using a Google Script) perfect for static websites that need to collect data.
Stars: โœญ 2,718 (+2263.48%)
Mutual labels:  tutorial, example, howto
Phoenix Ecto Encryption Example
๐Ÿ” A detailed example for how to encrypt data in a Phoenix (Elixir) App before inserting into a database using Ecto Types
Stars: โœญ 166 (+44.35%)
Mutual labels:  phoenix, tutorial, learn
Espressif
all espressif stuff will committed here
Stars: โœญ 477 (+314.78%)
Mutual labels:  tutorial, example, howto
Reactnativecodereuseexample
Shows how to organize your code to reuse it as much as possible between Web, iOS and Android
Stars: โœญ 41 (-64.35%)
Mutual labels:  tutorial, example, howto
Learn Heroku
๐Ÿ Learn how to deploy your web application to Heroku from scratch step-by-step in 7 minutes!
Stars: โœญ 110 (-4.35%)
Mutual labels:  tutorial, learn, beginner
Phoenix In Action
Code snippets and examples from the book Phoenix in Action from Manning and Geoffrey Lessel
Stars: โœญ 60 (-47.83%)
Mutual labels:  phoenix, phoenix-framework
Shorten api tutorial
๐Ÿ”—How to make a link shortener using Elixir, Phoenix and Mnesia
Stars: โœญ 60 (-47.83%)
Mutual labels:  phoenix, phoenix-framework
Hello World
๐Ÿ™† Are you a beginner? send your test pull requests here!
Stars: โœญ 70 (-39.13%)
Mutual labels:  learn, beginner
Learn Vim
Vim ๅฎžๆ“ๆ•™็จ‹๏ผˆLearning Vim๏ผ‰Vim practical tutorial.
Stars: โœญ 1,166 (+913.91%)
Mutual labels:  tutorial, beginner
React Redux Boilerplate
It is a boilerplate of React-Redux as the infrastructure, which helps to setup a Web APP quickly
Stars: โœญ 113 (-1.74%)
Mutual labels:  tutorial, example
Memento
Collect saved items from different sources around the web
Stars: โœญ 89 (-22.61%)
Mutual labels:  phoenix, phoenix-framework
Absolutebeginnerprojects
A repo for brand new devs who are looking for great real-world fundamental practice projects
Stars: โœญ 93 (-19.13%)
Mutual labels:  tutorial, beginner
Unityraymarching
Unity Raymarching Examples
Stars: โœญ 57 (-50.43%)
Mutual labels:  tutorial, example

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

๐Ÿ’ก 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. โœ…


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.4 (compiled with Erlang/OTP 23)

This informs us we are using Elixir version 1.10.4 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.5.5

If you have an earlier version, definitely upgrade to get the latest features!
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.18.4

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 dependencies by running the command:

mix setup

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 --live --no-ecto

The --live flag tells the mix phx.new generator command that we are creating a LiveView application. It will setup the dependencies and boilerplate for us to get going as fast as possible.

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, go into the newly created app folder using:

cd live_view_counter

And then 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

๐Ÿ˜ฑ If you are having problems with the server hanging, try this

๐Ÿ Snapshot of code at the end of Step 1: #c48488


Step 2. 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: "s0e+LZ/leTtv3peHaFhnd2rbncAeV5qlR1rNShKXDMSRbVgU2Aar8nyXszsQrZ1p",
  render_errors: [view: LiveViewCounterWeb.ErrorView, accepts: ~w(html json), layout: false],
  pubsub_server: LiveViewCounter.PubSub,
  live_view: [signing_salt: "tT2envDD"]

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: "s0e+LZ/leTtv3peHaFhnd2rbncAeV5qlR1rNShKXDMSRbVgU2Aar8nyXszsQrZ1p",
  render_errors: [view: LiveViewCounterWeb.ErrorView, accepts: ~w(html json), layout: false],
  pubsub_server: LiveViewCounter.PubSub,
  live_view: [signing_salt: "iluKTpVJp8PgtRHYv1LSItNuQ1bLdR7c"]

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

๐Ÿ At the end of Step 2 the 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.


Step 3: Add Phoenix.LiveView.Controller to live_view_counter_web.ex

Open the lib/live_view_counter_web.ex file and add the relevant Phoenix.LiveView import statement to the controller:

def controller do
  quote do
    use Phoenix.Controller, namespace: LiveViewCounterWeb

    import Plug.Conn
    import LiveViewCounterWeb.Gettext
    alias LiveViewCounterWeb.Router.Helpers, as: Routes

+   import Phoenix.LiveView.Controller
  end
end

๐Ÿ Change made in Step 3: lib/live_view_counter_web.ex#L28


We are finished setting up our Phoenix App to use LiveView! Now we get to the fun part: creating the counter!! ๐ŸŽ‰


Step 4: Create the counter.ex File

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)}
  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) }
end

In our case we are ignoring the _params and _session, hence the underscore prepended to the parameters. If we were using sessions for 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.


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 forth 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 4 you should have a file similar to: lib/live_view_counter_web/live/counter.ex


Step 5: Create the live Route in router.ex

Now that we have created our Live handler function in Step 4, 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 5 you should have a router.ex file similar to: lib/live_view_counter_web/router.ex#L20


5.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 disconnected and connected render (LiveViewCounterWeb.PageLiveTest)
   test/live_view_counter_web/live/page_live_test.exs:6
   Assertion with =~ failed
   code:  assert disconnected_html =~ "Welcome to Phoenix!"
   left:  "<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\"/><meta charset=\"UTF-8\" content=\"IHQLHHISBjZlWTskHjAmHBETKCFnGWUloYSOGMkDRhaSvIBtkycvQNUF\" csrf-param=\"_csrf_token\" method-param=\"_method\" name=\"csrf-token\"/><title data-suffix=\" ยท Phoenix Framework\">LiveViewCounter ยท Phoenix Framework</title><link phx-track-static=\"phx-track-static\" rel=\"stylesheet\" href=\"/css/app.css\"/><script defer=\"defer\" phx-track-static=\"phx-track-static\" type=\"text/javascript\" src=\"/js/app.js\"></script></head><body><header><section class=\"container\"><nav role=\"navigation\"><ul><li><a href=\"https://hexdocs.pm/phoenix/overview.html\">Get Started</a></li><li><a href=\"/dashboard\">LiveDashboard</a></li></ul></nav><a href=\"https://phoenixframework.org/\" class=\"phx-logo\"><img src=\"/images/phoenix.png\" alt=\"Phoenix Framework Logo\"/></a></section></header><div data-phx-main=\"true\" data-phx-session=\"SFMyNTY" data-phx-view=\"Counter\" id=\"phx-FhQ9AJF6KACJPAEm\"><div><h1>The count is: 0</h1><button phx-click=\"dec\">-</button><button phx-click=\"inc\">+</button></div></div></body></html>"
   right: "Welcome to Phoenix!"
   stacktrace:
     test/live_view_counter_web/live/page_live_test.exs:8: (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/live/page_live_test.exs file and locate the lines:

assert disconnected_html =~ "Welcome to Phoenix!"
assert render(page_live) =~ "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_live_test.exs file should now look like this: test/live_view_counter_web/live/page_live_test.exs#L8-L9

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 was 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 6: 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)}
  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 the @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).

๐Ÿ At the end of Step 6 the file looks like: lib/live_view_counter_web/live/counter.ex


Checkpoint: Run It!

Now that counter.ex has been updated 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!


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!




Future Steps

Moving state out of the LiveViews

With this implementation you may have noticed that when we open a new browser window the count is always zero. As soon as we click plus or minus it adjusts and all the views get back in line. This is because the state is replicated across LiveView instances and coordinated via pub-sub. If the state was big and complicated this would get wasteful in resources and hard to manage.

Generally it is good practice to identify shared state and to manage that in a single location.

The Elixir way of managing state is the GenServer, using PubSub to update the LiveViews about changes. This allows the LiveViews to focus on user specific state, separating concerns; making the application both more efficient (hopefully) and easier to reason about and debug.

We are now going to start making use of the lib/live_view_counter directory! The Phoenix docs says that this holds "all of your business domain". For us this is the current count, along with the incr and decr methods.

defmodule LiveViewCounter.Count do
  use GenServer

  alias Phoenix.PubSub

  @name :count_server

  @start_value 0

  # -------  External API (runs in client process) -------

  def topic do
    "count"
  end

  def start_link(_opts) do
    GenServer.start_link(__MODULE__, @start_value, name: @name)
  end

  def incr() do
    GenServer.call @name, :incr
  end

  def decr() do
    GenServer.call @name, :decr
  end

  def current() do
    GenServer.call @name, :current
  end

  def init(start_count) do
    {:ok, start_count}
  end

  # -------  Implementation  (Runs in GenServer process) -------

  def handle_call(:current, _from, count) do
     {:reply, count, count}
  end

  def handle_call(:incr, _from, count) do
    make_change(count, +1)
  end

  def handle_call(:decr, _from, count) do
    make_change(count, -1)
  end

  defp make_change(count, change) do
    new_count = count + change
    PubSub.broadcast(LiveViewCounter.PubSub, topic(), {:count, new_count})
    {:reply, new_count, new_count}
  end
end

The GenServer runs in its own process. Other parts of the application invoke the API in their own process, these calls are forwarded to the handle_call functions in the GenServer process where they are processed serially.

We have also moved the PubSub publication here as well.

[We could have used asyncronous handle_cast functions and relied on the PubSub to update us. Using handle_call means the calling LiveView will be updated twice, but it doesn't really matter at this scale.]

We are also going to need to tell the Application that it now has some business logic; we do this in the start/2 function in the lib/live_view_counter/application.ex file.

  def start(_type, _args) do
    children = [
      # Start the App State
+     LiveViewCounter.Count,
      # Start the Telemetry supervisor
      LiveViewCounterWeb.Telemetry,
      # Start the PubSub system
      {Phoenix.PubSub, name: LiveViewCounter.PubSub},
      # Start the Endpoint (http/https)
      LiveViewCounterWeb.Endpoint
      # Start a worker by calling: LiveViewCounter.Worker.start_link(arg)
      # {LiveViewCounter.Worker, arg}
    ]

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: LiveViewCounter.Supervisor]
    Supervisor.start_link(children, opts)
  end
...

Finally, we are going to have to make some changes to the LiveView itself, it now has less to do!

defmodule LiveViewCounterWeb.Counter do
  use Phoenix.LiveView
  alias LiveViewCounter.Count
  alias Phoenix.PubSub

  @topic Count.topic

  def mount(_params, _session, socket) do
    PubSub.subscribe(LiveViewCounter.PubSub, @topic)

    {:ok, assign(socket, val: Count.current()) }
  end

  def handle_event("inc", _, socket) do
    {:noreply, assign(socket, :val, Count.incr())}
  end

  def handle_event("dec", _, socket) do
    {:noreply, assign(socket, :val, Count.decr())}
  end

  def handle_info({:count, count}, socket) do
    {:noreply, assign(socket, val: count)}
  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

What is happening now is that the initial state is being retrieved from the shared Application GenServer process and the updates are being forwarded there via its API. Finally, the Gen Server Handlers publish the new state to all the active LiveViews.

How many people are using the Counter?

Phoenix has a very cool feature called Presence to track how many people are using our system. (It does a lot more than count users, but this is a counting app so...)

First of all we need to tell the Application we are going to use Presence. For this we need to create a lib/lib_view_counter/presence.ex file like this:

defmodule LiveViewCounter.Presence do
  use Phoenix.Presence,
    otp_app: :live_view_counter,
    pubsub_server: LiveViewCounter.PubSub
end

and tell the application about it in the lib/lib_view_counter/application.ex file (add it just below the PubSub config):

  def start(_type, _args) do
    children = [
      # Start the App State
      LiveViewCounter.Count,
      # Start the Telemetry supervisor
      LiveViewCounterWeb.Telemetry,
      # Start the PubSub system
      {Phoenix.PubSub, name: LiveViewCounter.PubSub},
+     LiveViewCounter.Presence,
      # Start the Endpoint (http/https)
      LiveViewCounterWeb.Endpoint
      # Start a worker by calling: LiveViewCounter.Worker.start_link(arg)
      # {LiveViewCounter.Worker, arg}
    ]

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: LiveViewCounter.Supervisor]
    Supervisor.start_link(children, opts)
  end

The application doesn't need to know any more about the user count (it might, but not here) so the rest of the code goes into lib/lib_view_counter_web/live/counter.ex.

  1. We subscribe, participate-in and subscribe to the Presence system (we do that in mount)
  2. We handle Presence updates and use the current count, adding joiners and subtracting leavers to calculate the current numbers 'present'. We do that in a pattern matched handle_info.
  3. We publish the additional data to the client in render
defmodule LiveViewCounterWeb.Counter do
  use Phoenix.LiveView
  alias LiveViewCounter.Count
  alias Phoenix.PubSub
  alias LiveViewCounter.Presence

  @topic Count.topic
  @presence_topic "presence"

  def mount(_params, _session, socket) do
    PubSub.subscribe(LiveViewCounter.PubSub, @topic)

+   Presence.track(self(), @presence_topic, socket.id, %{})
+   LiveViewCounterWeb.Endpoint.subscribe(@presence_topic)
+
+   initial_present =
+     Presence.list(@presence_topic)
+     |> map_size

+   {:ok, assign(socket, val: Count.current(), present: initial_present) }
-   {:ok, assign(socket, val: Count.current()) }
  end

  def handle_event("inc", _, socket) do
    {:noreply, assign(socket, :val, Count.incr())}
  end

  def handle_event("dec", _, socket) do
    {:noreply, assign(socket, :val, Count.decr())}
  end

  def handle_info({:count, count}, socket) do
    {:noreply, assign(socket, val: count)}
  end

+ def handle_info(
+       %{event: "presence_diff", payload: %{joins: joins, leaves: leaves}},
+       %{assigns: %{present: present}} = socket
+    ) do
+   new_present = present + map_size(joins) - map_size(leaves)
+
+   {:noreply, assign(socket, :present, new_present)}
+ end

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

Now, as you open and close your incognito windows you will get a count of how many are running.




Notes and help

Problems with dependencies

If the app hangs and throws this error:

[error] an exception was raised:
    ** (FunctionClauseError) no function clause matching in Phoenix.LiveView.Channel.start_link/1
        (phoenix_live_view 0.12.1) lib/phoenix_live_view/channel.ex:12: Phoenix.LiveView.Channel.start_link({LivetestWeb.Endpoint, {#PID<0.643.0>, #Reference<0.4273921409.1426587651.156349>}})

Modifying your mix.deps from:

 defp deps do
    [
      {:phoenix, "~> 1.5.1"},
      {:phoenix_live_view, "~> 0.12.1"},
      ...
    ]
  end

to this:

 defp deps do
    [
      {:phoenix, "~> 1.5.3"},
      {:phoenix_live_view, "~> 0.13.0"},
      ...
    ]
  end

Should fix the problem.


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/

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].