Giter VIP home page Giter VIP logo

dwyl / phoenix-liveview-counter-tutorial Goto Github PK

View Code? Open in Web Editor NEW
346.0 98.0 35.0 1.01 MB

๐Ÿคฏ beginners tutorial building a real time counter in Phoenix 1.7.7 + LiveView 0.19 โšก๏ธ Learn the fundamentals from first principals so you can make something amazing! ๐Ÿš€

Home Page: https://livecount.fly.dev/

License: GNU General Public License v2.0

Elixir 71.09% CSS 0.18% JavaScript 4.90% HTML 20.57% Dockerfile 3.10% Shell 0.09% Batchfile 0.06%
phoenix-liveview counter tutorial example learn elixir phoenix phoenix-framework beginner how-to

phoenix-liveview-counter-tutorial's Introduction

Phoenix LiveView Counter Tutorial

GitHub Workflow Status codecov.io Hex.pm contributions welcome HitCount

Build your first App using Phoenix LiveView ๐Ÿฅ‡
and understand all the concepts in 10 minutes or less! ๐Ÿš€
Try it: livecount.fly.dev



Why? ๐Ÿคทโ€โ™€๏ธ

There are several apps around the Internet that use Phoenix LiveView but none include step-by-step instructions a complete beginner can follow ... ๐Ÿ˜•
This is the complete beginner's tutorial we wish we had when learning LiveView and the one you have been searching 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 writing JavaScript! This enables building incredible interactive experiences with considerably less code.

LiveView pages load instantly because they are rendered on the Server and they require far 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.

For a sneak peak of what is possible to build with LiveView, watch @chrismccord's LiveBeats intro:

Phoenix.LiveView.LiveBeats.Demo.mp4

Tip: Enable the sound. It's a collaborative music listening experience. ๐ŸŽถ Try the LiveBeats Demo: livebeats.fly.dev ๐Ÿ˜ ๐Ÿคฏ ๐Ÿ™


Who? ๐Ÿ‘ค

This tutorial is aimed at people who have never built anything in Phoenix or LiveView. You can speed-run it in 10 minutes if you're already familiar with Phoenix or Rails.

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.

Please Star! โญ

This is the tutorial we wish we'd had when we first started using LiveView ...
If you find it useful, please give it a star โญ it on Github so that other people will discover it.

Thanks! ๐Ÿ™


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

This informs us we are using Elixir version 1.15.4 which is the latest version at the time of writing. Some of the more advanced features of Phoenix 1.7 during compilation time require elixir 1.14 although the code will work in previous versions.


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

If you run the following command in your terminal:

mix phx.new -v

You should see something similar to the following:

Phoenix installer v1.7.7

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. Basic familiarity with Elixir syntax is recommended but not essential;
If you know any programming language, 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 Fly.io: livecount.fly.dev


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 something similar to the following:

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 counter --no-ecto --no-mailer --no-dashboard --no-gettext

The flags after the counter (name of the project), tell mix phx.new generator:

  • --no-ecto - don't create a Database - we aren't storing any data
  • --no-mailer- this project doesn't send email
  • --no-dashboard - we don't need a status dashboard
  • --no-gettext - no translation required

This keeps our counter as simple as possible. We can always add these features later if needed.

Note: Since Phoenix 1.6 the --live flag is no longer required when creating a LiveView app. LiveView is included by default in all new Phoenix Apps. Older tutorials may still include the flag, everything is much easier now. ๐Ÿ˜‰

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:

cd counter

And then run the following mix command:

mix test

This will compile the Phoenix app and will take some time. โณ
You should see output similar to this:

Compiling 13 files (.ex)
Generated counter app
.....
Finished in 0.00 seconds (0.00s async, 0.00s sync)
5 tests, 0 failures

Randomized with seed 29485

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.

You should see something similar to the following:

welcome-to-phoenix


Step 2: Create the counter.ex File

Create a new file with the path: lib/counter_web/live/counter.ex

And add the following code to it:

defmodule CounterWeb.Counter do
  use CounterWeb, :live_view

  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
    ~H"""
    <div>
    <h1 class="text-4xl font-bold text-center"> The count is: <%= @val %> </h1>

    <p class="text-center">
     <.button phx-click="dec">-</.button>
     <.button phx-click="inc">+</.button>
     </p>
     </div>
    """
  end
end

Explanation of the Code

The first line instructs Phoenix to use the Phoenix.LiveView behaviour. This just means that we need to implement certain functions for our LiveView 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 arguments, hence the prepended underscore. If we were using sessions, 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 initialized 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: elixirschool.com/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 ~H""" syntax just means "treat this multiline string as a LiveView template" The ~H 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 2 you should have a file similar to: lib/counter_web/live/counter.ex


Step 3: Create the live Route in router.ex

Now that we have created our LiveView handler functions in Step 2, it's time to tell Phoenix how to find it.

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

scope "/", CounterWeb do
  pipe_through :browser

  get "/", PageController, :index
end

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

scope "/", CounterWeb do
  pipe_through :browser

  live("/", Counter)
end

3.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/counter_web/controllers/page_controller_test.exs will now fail:

Compiling 6 files (.ex)
Generated counter app
....

  1) test GET / (CounterWeb.PageControllerTest)
     test/counter_web/controllers/page_controller_test.exs:4
     Assertion with =~ failed
     code:  assert html_response(conn, 200) =~ "Peace of mind from prototype to production"
     left:  "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n    <meta name=\"csrf-token\" content=\"EFt5PABkPz1nPg5FMAoaDSA6BCFtBCMO_4JmNTx_2vO6i3qxXjETTpal\">\n    <title data-suffix=\" ยท Phoenix Framework\">\nLiveViewCounter\n     ยท Phoenix Framework</title>\n    <link phx-track-static rel=\"stylesheet\" href=\"/assets/app.css\">\n    <script defer phx-track-static type=\"text/javascript\" src=\"/assets/app.js\">\n    </script>\n  </head>\n  <body class=\"bg-white antialiased\">\n<div data-phx-main=\"true\" data-phx-session=\"SFMyNTY.g2gDaA\" id=\"phx-Fyi3ICCa7vPqDADE\"><header class=\"px-4 sm:px-6 lg:px-8\">\n  <div class=\"flex items-center justify-between border-b border-zinc-100 py-3\">\n    <div class=\"flex items-center gap-4\">\n      <a href=\"/\">\n        <svg viewBox=\"0 0 71 48\" class=\"h-6\" aria-hidden=\"true\">\n          <path d=\"etc." fill=\"#FD4F00\"></path>\n        </svg>\n      </a>\n      <p class=\"rounded-full bg-brand/5 px-2 text-[0.8125rem] font-medium leading-6 text-brand\">\n        v1.7\n      </p>\n    </div>\n    <div class=\"flex items-center gap-4\">\n      <a href=\"https://twitter.com/elixirphoenix\" class=\"text-[0.8125rem] font-semibold leading-6 text-zinc-900 hover:text-zinc-700\">\n        @elixirphoenix\n      </a>\n      <a href=\"https://github.com/phoenixframework/phoenix\" class=\"text-[0.8125rem] font-semibold leading-6 text-zinc-900 hover:text-zinc-700\">\n        GitHub\n      </a>\n      <a href=\"https://hexdocs.pm/phoenix/overview.html\" class=\"rounded-lg bg-zinc-100 px-2 py-1 text-[0.8125rem] font-semibold leading-6 text-zinc-900 hover:bg-zinc-200/80 active:text-zinc-900/70\">\n        Get Started <span aria-hidden=\"true\">&rarr;</span>\n      </a>\n    </div>\n  </div>\n</header>\n<main class=\"px-4 py-20 sm:px-6 lg:px-8\">\n </p>\n  \n</div>\n<div>\n<h1 class=\"text-4xl font-bold text-center\"> The count is: 0 </h1>\n\n<p class=\"text-center\">\n <button class=\"phx-submit-loading:opacity-75 rounded-lg bg-zinc-900 hover:bg-zinc-700 py-2 px-3 text-sm font-semibold leading-6 text-white active:text-white/80 \" phx-click=\"dec\">\n  -\n</button>\n <button class=\"phx-submit-loading:opacity-75 rounded-lg bg-zinc-900 hover:bg-zinc-700 py-2 px-3 text-sm font-semibold leading-6 text-white active:text-white/80 \" phx-click=\"inc\">\n  +\n</button>\n </p>\n </div>\n  </div>\n</main></div>\n  </body>\n</html>"
     right: "Peace of mind from prototype to production"
     stacktrace:
       test/counter_web/controllers/page_controller_test.exs:6: (test)


Finished in 0.1 seconds (0.06s async, 0.09s sync)
5 tests, 1 failure

This just tells us that the test is looking for the string "Peace of mind from prototype to production" in the page and did not find it.

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

assert html_response(conn, 200) =~ "Peace of mind from prototype to production"

Update the string from "Peace of mind from prototype to production" to something we know is present on the page, e.g: "The count is"

๐Ÿ The page_controller_test.exs.exs file should now look like this: test/counter_web/controllers/page_controller_test.exs#L6

Confirm the tests pass again by running:

mix test

You should see output similar to:

.....
Finished in 0.08 seconds (0.03s async, 0.05s sync)
5 tests, 0 failures

Randomized with seed 268653

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:

liveview-counter-1.7.7


Recap: Working Counter Without Writing JavaScript!

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/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 (relevant) 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 4: 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 Phoenix Channels. Channels allow us to effortlessly sync data between clients and servers with minimal overhead; they are one of Elixir (Erlang/OTP) superpowers!

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

defmodule CounterWeb.Counter do
  use CounterWeb, :live_view

  @topic "live"

  def mount(_session, _params, socket) do
    CounterWeb.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))
    CounterWeb.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))
    CounterWeb.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
    ~H"""
    <div class="text-center">
      <h1 class="text-4xl font-bold text-center"> Counter: <%= @val %> </h1>
      <.button phx-click="dec" class="w-20 bg-red-500 hover:bg-red-600">-</.button>
      <.button phx-click="inc" class="w-20 bg-green-500 hover:bg-green-600">+</.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:

CounterWeb.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.

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))
  CounterWeb.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 CounterWeb.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: CounterWeb.Counter,
    val: 1
  },
  changed: %{val: true},
  endpoint: CounterWeb.Endpoint,
  id: "phx-Ffq41_T8jTC_3gED",
  parent_pid: nil,
  view: CounterWeb.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))
  CounterWeb.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, val: msg.payload.val)}
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, val: msg.payload.val)} just means "don't send this message to the socket again" (which would cause a recursive loop of updates).

Finally we modified the HTML inside the render/1 function to be a bit more visually appealing.

๐Ÿ At the end of Step 6 the file looks like: lib/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!


Tests! ๐Ÿงช

before we get carried away celebrating that we've finished the counter, Let's make sure that all the functionality, however basic, is fully tested.

Add excoveralls to Check/Track Coverage

Open your mix.exs file and locate the deps list. Add the following line to the list:

# Track test coverage: github.com/parroty/excoveralls
{:excoveralls, "~> 0.16.0", only: [:test, :dev]},

e.g: mix.exs#L58

Then, still in the mix.exs file, locate the project definition, and replace:

deps: deps()

With the following lines:

deps: deps(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
  c: :test,
  coveralls: :test,
  "coveralls.detail": :test,
  "coveralls.json": :test,
  "coveralls.post": :test,
  "coveralls.html": :test,
  t: :test
]

e.g: mix.exs#L13-L22

Finally in the aliases section of mix.exs, add the following lines:

c: ["coveralls.html"],
s: ["phx.server"],
t: ["test"]

The mix c alias is the one we care about, we're going to use it immediately. The other two mix s and mix t are convenient shortcuts too. Hopefully you can infer what they do. ๐Ÿ‘Œ

With the the mix.exs file updated, run the following commands in your terminal:

mix deps.get
mix c

That will download the excoveralls dependency and execute the tests with coverage tracking.

You should see output similar to the following:

Randomized with seed 468341
----------------
COV    FILE                                        LINES RELEVANT   MISSED
100.0% lib/counter.ex                                  9        0        0
 75.0% lib/counter/application.ex                     34        4        1
100.0% lib/counter_web.ex                            111        2        0
 15.9% lib/counter_web/components/core_componen      661      151      127
100.0% lib/counter_web/components/layouts.ex           5        0        0
100.0% lib/counter_web/controllers/error_html.e       19        1        0
100.0% lib/counter_web/controllers/error_json.e       15        1        0
  0.0% lib/counter_web/controllers/page_control        9        1        1
100.0% lib/counter_web/controllers/page_html.ex        5        0        0
100.0% lib/counter_web/endpoint.ex                    46        0        0
 33.3% lib/counter_web/live/counter.ex                32       12        8
100.0% lib/counter_web/live/counter_component.e       17        2        0
100.0% lib/counter_web/router.ex                      18        2        0
 80.0% lib/counter_web/telemetry.ex                   69        5        1
[TOTAL]  23.8%
----------------
Generating report...
Saved to: cover/
FAILED: Expected minimum coverage of 100%, got 23.8%.

This tells us that only 23.8% of the code in the project is covered by tests. ๐Ÿ˜• Let's fix that!

Create a coveralls.json File

In the root of the project, create a file called coveralls.json and add the following code to it:

{
  "coverage_options": {
    "minimum_coverage": 100
  },
  "skip_files": [
    "lib/counter/application.ex",
    "lib/counter_web.ex",
    "lib/counter_web/channels/user_socket.ex",
    "lib/counter_web/telemetry.ex",
    "lib/counter_web/views/error_helpers.ex",
    "lib/counter_web/router.ex",
    "lib/counter_web/live/page_live.ex",
    "lib/counter_web/components/core_components.ex",
    "lib/counter_web/controllers/error_json.ex",
    "lib/counter_web/controllers/error_html.ex",
    "test/"
  ]
}

This file and the skip_files list specifically, tells excoveralls to ignore boilerplate Phoenix files we cannot test.

If you re-run mix c now you should see something similar to the following:

Randomized with seed 572431
----------------
COV    FILE                                        LINES RELEVANT   MISSED
100.0% lib/counter.ex                                  9        0        0
100.0% lib/counter_web/components/layouts.ex           5        0        0
  0.0% lib/counter_web/controllers/page_control        9        1        1
100.0% lib/counter_web/controllers/page_html.ex        5        0        0
100.0% lib/counter_web/endpoint.ex                    46        0        0
 33.3% lib/counter_web/live/counter.ex                32       12        8
[TOTAL]  40.0%
----------------
Generating report...
Saved to: cover/
FAILED: Expected minimum coverage of 100%, got 40%.

This is already much better. There are only 2 files we need to focus on. Let's start by tidying up the unused files.

DELETE Unused Files

Given that this counter App doesn't use any "controllers", we can simply DELETE the lib/counter_web/controllers/page_controller.ex file.

git rm lib/counter_web/controllers/page_controller.ex

Rename the test/counter_web/controllers/page_controller_test.exs to: test/counter_web/live/counter_test.exs

Update the code in the test/counter_web/live/counter_test.exs to:

defmodule CounterWeb.CounterTest do
  use CounterWeb.ConnCase
  import Phoenix.LiveViewTest

  test "connected mount", %{conn: conn} do
    {:ok, _view, html} = live(conn, "/")
    assert html =~ "Counter: 0"
  end
end

Re-run the tests:

mix c

You should see:

Finished in 0.1 seconds (0.04s async, 0.07s sync)
6 tests, 0 failures

Randomized with seed 603239
----------------
COV    FILE                                        LINES RELEVANT   MISSED
100.0% lib/counter.ex                                  9        0        0
100.0% lib/counter_web/components/layouts.ex           5        0        0
100.0% lib/counter_web/controllers/page_html.ex        5        0        0
100.0% lib/counter_web/endpoint.ex                    46        0        0
 33.3% lib/counter_web/live/counter.ex                32       12        8
[TOTAL]  42.9%
----------------
Generating report...
Saved to: cover/
FAILED: Expected minimum coverage of 100%, got 42.9%.

Open the coverage HTML file:

open cover/excoveralls.html

You should see:

image

This shows us which functions/lines are not being covered by our existing tests.


Add More Tests!

Open the test/counter_web/live/counter_test.exs and add the following tests:

test "Increment", %{conn: conn} do
  {:ok, view, _html} = live(conn, "/")
  assert render_click(view, :inc) =~ "Counter: 1"
end

test "Decrement", %{conn: conn} do
  {:ok, view, _html} = live(conn, "/")
  assert render_click(view, :dec) =~ "Counter: -1"
end

test "handle_info/2 broadcast message", %{conn: conn} do
  {:ok, view, _html} = live(conn, "/")
  {:ok, view2, _html} = live(conn, "/")

  assert render_click(view, :inc) =~ "Counter: 1"
  assert render_click(view2, :inc) =~ "Counter: 2"
end

Once you've saved the file, re-run the tests: mix c You should see:

........
Finished in 0.1 seconds (0.03s async, 0.09s sync)
8 tests, 0 failures

Randomized with seed 552859
----------------
COV    FILE                                        LINES RELEVANT   MISSED
100.0% lib/counter.ex                                  9        0        0
100.0% lib/counter_web/components/layouts.ex           5        0        0
100.0% lib/counter_web/controllers/page_html.ex        5        0        0
100.0% lib/counter_web/endpoint.ex                    46        0        0
100.0% lib/counter_web/live/counter.ex                32       12        0
[TOTAL] 100.0%
----------------

Done. โœ…

Bonus Level: Use a LiveView Component (Optional)

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

def render(assigns) do
  ~H"""
  <div class="text-center">
    <h1 class="text-4xl font-bold text-center"> Counter: <%= @val %> </h1>
    <.button phx-click="dec" class="text-6xl pb-2 w-20 bg-red-500 hover:bg-red-600">-</.button>
    <.button phx-click="inc" class="text-6xl pb-2 w-20 bg-green-500 hover:bg-green-600">+</.button>
  </div>
  """

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

This is where Phoenix.LiveComponent comes to the rescue! LiveComponents are a mechanism to compartmentalize state, markup, and events in LiveView.

Create a LiveView Component

Create a new file with the path: lib/counter_web/live/counter_component.ex

And type (or paste) the following code in it:

defmodule CounterComponent do
  use Phoenix.LiveComponent

  # Avoid duplicating Tailwind classes and show hot to inline a function call:
  defp btn(color) do
    "text-6xl pb-2 w-20 rounded-lg bg-#{color}-500 hover:bg-#{color}-600"
  end

  def render(assigns) do
    ~H"""
    <div class="text-center">
      <h1 class="text-4xl font-bold text-center"> Counter: <%= @val %> </h1>
      <button phx-click="dec" class={btn("red")}>
        -
      </button>
      <button phx-click="inc" class={btn("green")}>
        +
      </button>
    </div>
    """
  end
end

Then back in the counter.ex file, update the render/1 function to:

  def render(assigns) do
    ~H"""
    <.live_component module={CounterComponent} id="counter" val={@val} />
    """
  end

๐Ÿ Your counter_component.ex should look like this: lib/counter_web/live/counter_component.ex

The component has a similar render/1 function to what was in counter.ex. That's the point; we just want it in a separate file for maintainability.


Re-run the counter App using mix phx.server and confirm everything still works:

phoenix-liveview-counter-component

The tests all still pass and we have 100% coverage:

........
Finished in 0.1 seconds (0.03s async, 0.09s sync)
8 tests, 0 failures

Randomized with seed 470293
----------------
COV    FILE                                        LINES RELEVANT   MISSED
100.0% lib/counter.ex                                  9        0        0
100.0% lib/counter_web/components/layouts.ex           5        0        0
100.0% lib/counter_web/controllers/page_html.ex        5        0        0
100.0% lib/counter_web/endpoint.ex                    46        0        0
100.0% lib/counter_web/live/counter.ex                32       12        0
100.0% lib/counter_web/live/counter_component.e       17        2        0
[TOTAL] 100.0%
----------------

Moving state out of the LiveView

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 LiveView about changes. This allows the LiveViews to focus on specific state, separating concerns; making the application both more efficient (hopefully) and easier to reason about and debug.

Create a file with the path: lib/counter_web/live/counter_state.ex and add the following:

defmodule Counter.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(Counter.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 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/counter/application.ex file.

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

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

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

defmodule CounterWeb.Counter do
  use CounterWeb, :live_view
  alias Counter.Count
  alias Phoenix.PubSub

  @topic Count.topic

  def mount(_params, _session, socket) do
    PubSub.subscribe(Counter.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
    ~H"""
    <div>
      <h1>The count is: <%= @val %></h1>
      <.button phx-click="dec">-</.button>
      <.button phx-click="inc">+</.button>
    </div>
    """
  end
end

The initial state is retrieved from the shared Application GenServer process and the updates are being forwarded there via its API. Finally, the GenServer to all the active LiveView clients.

Update the Tests for GenServer State

Given that the counter.ex is now using the GenServer State, two of the tests now fail because the count is not correct.

mix t

Generated counter app
.....

  1) test connected mount (CounterWeb.CounterTest)
     test/counter_web/live/counter_test.exs:6
     Assertion with =~ failed
     code:  assert html =~ "Counter: 0"
     left:  "<html lang=\"en\" class=\"[scrollbar-gutter:stable]\"><head><meta charset=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/><meta name=\"csrf-token\" content=\"A2QQMHc0OgsbDl0mUCZdGDoHWhUtMC4CDUIv9XHhtx2p6_iLerkvIbbk\"/><title data-suffix=\" ยท Phoenix Framework\">\nCounter\n     ยท Phoenix Framework</title><link phx-track-static=\"phx-track-static\" rel=\"stylesheet\" href=\"/assets/app.css\"/><script defer=\"defer\" phx-track-static=\"phx-track-static\" type=\"text/javascript\" src=\"/assets/app.js\">\n    </script></head><body class=\"bg-white antialiased\"><div data-phx-main=\"data-phx-main\" data-phx-session=\"SFMyNTY.g2gDaAJhBXQAAAAIdwJpZG0AAAAUcGh4LUYzWm01LWgycVNXZW5RREJ3B3Nlc3Npb250AAAAAHcKcGFyZW50X3BpZHcDbmlsdwZyb3V0ZXJ3GEVsaXhpci5Db3VudGVyV2ViLlJvdXRlcncEdmlld3cZRWxpeGlyLkNvdW50ZXJXZWIuQ291bnRlcncIcm9vdF9waWR3A25pbHcJcm9vdF92aWV3dxlFbGl4aXIuQ291bnRlcldlYi5Db3VudGVydwxsaXZlX3Nlc3Npb25oAncHZGVmYXVsdG4IAPP26BwRWHYXbgYA2w20ookBYgABUYA.Zae9BLTboLn6SPPe0qmktsfuru8HX2W4CALIBZNpcqE\" data-phx-static=\"SFMyNTY.g2gDaAJhBXQAAAADdwJpZG0AAAAUcGh4LUYzWm01LWgycVNXZW5RREJ3BWZsYXNodAAAAAB3CmFzc2lnbl9uZXdqbgYA2w20ookBYgABUYA.uooN8p97RRE1JN4tmkVNqC9islv-Np5B8wrewhwLnKc\" id=\"phx-F3Zm5-h2qSWenQDB\"><header class=\"px-4 sm:px-6 lg:px-8\"><div class=\"flex items-center justify-between border-b border-zinc-100 py-3 text-sm\"><div class=\"flex items-center gap-4\"><a href=\"/\"><img src=\"/images/logo.svg\" width=\"36\"/></a><p class=\"bg-brand/5 text-brand rounded-full px-2 font-medium leading-6\">\n        v1.7.7\n      </p></div><div class=\"flex items-center gap-4 font-semibold leading-6 text-zinc-900\"><a href=\"https://github.com/dwyl/phoenix-liveview-counter-tutorial\" class=\"hover:text-zinc-700\">\n        GitHub\n      </a><a href=\"https://github.com/dwyl/phoenix-liveview-counter-tutorial#how-\" class=\"rounded-lg bg-zinc-100 px-2 py-1 hover:bg-zinc-200/80\">\n        Get Started ..."
     right: "Counter: 0"
     stacktrace:
       test/counter_web/live/counter_test.exs:8: (test)



  2) test Increment (CounterWeb.CounterTest)
     test/counter_web/live/counter_test.exs:11
     Assertion with =~ failed
     code:  assert render_click(view, :inc) =~ "Counter: 1"
     left:  "<header class=\"px-4 sm:px-6 lg:px-8\"><div class=\"flex items-center justify-between border-b border-zinc-100 py-3 text-sm\"><div class=\"flex items-center gap-4\"><a href=\"/\"><img src=\"/images/logo.svg\" width=\"36\"/></a><p class=\"bg-brand/5 text-brand rounded-full px-2 font-medium leading-6\">\n        v1.7.7\n      </p></div><div class=\"flex items-center gap-4 font-semibold leading-6 text-zinc-900\"><a href=\"https://github.com/dwyl/phoenix-liveview-counter-tutorial\" class=\"hover:text-zinc-700\">\n        GitHub\n      </a><a href=\"https://github.com/dwyl/phoenix-liveview-counter-tutorial#how-\" class=\"rounded-lg bg-zinc-100 px-2 py-1 hover:bg-zinc-200/80\">\n      etc..."
     right: "Counter: 1"
     stacktrace:
       test/counter_web/live/counter_test.exs:13: (test)

.
Finished in 0.1 seconds (0.02s async, 0.09s sync)
8 tests, 2 failures

The test is expecting the initial state to be 0 (zero) each time. But if we are storing the count in the GenServer, it will not be 0.

We can easily update the tests to check the state before incrementing/decrementing it. Open the test/counter_web/live/counter_test.exs file and replace the contents with the following:

defmodule CounterWeb.CounterTest do
  use CounterWeb.ConnCase
  import Phoenix.LiveViewTest

  test "Increment", %{conn: conn} do
    {:ok, view, html} = live(conn, "/")
    current = Counter.Count.current()
    assert html =~ "Counter: #{current}"
    assert render_click(view, :inc) =~ "Counter: #{current + 1}"
  end

  test "Decrement", %{conn: conn} do
    {:ok, view, html} = live(conn, "/")
    current = Counter.Count.current()
    assert html =~ "Counter: #{current}"
    assert render_click(view, :dec) =~ "Counter: #{current - 1}"
  end

  test "handle_info/2 Count Update", %{conn: conn} do
    {:ok, view, disconnected_html} = live(conn, "/")
    current = Counter.Count.current()
    assert disconnected_html =~ "Counter: #{current}"
    assert render(view) =~ "Counter: #{current}"
    send(view.pid, {:count, 2})
    assert render(view) =~ "Counter: 2"
  end
end

Re-run the tests mix c and watch them pass with 100% coverage:

.......
Finished in 0.1 seconds (0.04s async, 0.09s sync)
7 tests, 0 failures

Randomized with seed 614997
----------------
COV    FILE                                        LINES RELEVANT   MISSED
100.0% lib/counter.ex                                  9        0        0
100.0% lib/counter_web/components/layouts.ex           5        0        0
100.0% lib/counter_web/controllers/page_html.ex        5        0        0
100.0% lib/counter_web/endpoint.ex                    46        0        0
100.0% lib/counter_web/live/counter.ex                31        7        0
100.0% lib/counter_web/live/counter_component.e       17        2        0
100.0% lib/counter_web/live/counter_state.ex          53       12        0
[TOTAL] 100.0%
----------------

How many people are viewing the Counter?

Phoenix has a very cool feature called Presence to track how many people (connected clients) are using our system. It does a lot more than count clients, 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/counter/presence.ex file and add the following lines of code:

defmodule Counter.Presence do
  use Phoenix.Presence,
    otp_app: :counter,
    pubsub_server: Counter.PubSub
end

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

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

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: Counter.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/counter_web/live/counter.ex.

  1. We subscribe to and participate in 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 CounterWeb.Counter do
  use CounterWeb, :live_view
  alias Counter.Count
  alias Phoenix.PubSub
+ alias Counter.Presence

  @topic Count.topic
+ @presence_topic "presence"

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

+   Presence.track(self(), @presence_topic, socket.id, %{})
+   CounterWeb.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
    ~H"""
    <.live_component module={CounterComponent} id="counter" val={@val} />
+   <.live_component module={PresenceComponent} id="presence" present={@present} />
    """
  end
end

You will have noticed that last addition in the render/1 function invokes a PresenceComponent. It doesn't exist yet, let's create it now!

Create a file with the path: lib/counter_web/live/presence_component.ex and add the following code to it:

defmodule PresenceComponent do
  use Phoenix.LiveComponent

  def render(assigns) do
    ~H"""
    <h1 class="text-center pt-2 text-xl">Connected Clients: <%= @present %></h1>
    """
  end
end

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

dwyl-liveview-counter-presence-genserver-state


More Tests!

Once you have implemented the solution, you need to make sure that the new code is tested. Open the test/counter_web/live/counter_test.exs file and add the following tests:

test "handle_info/2 Presence Update - Joiner", %{conn: conn} do
  {:ok, view, html} = live(conn, "/")
  assert html =~ "Connected Clients: 1"
  send(view.pid, %{
    event: "presence_diff",
    payload: %{joins: %{"phx-Fhb_dqdqsOCzKQAl" => %{metas: [%{phx_ref: "Fhb_dqdrwlCmfABl"}]}},
                leaves: %{}}})
  assert render(view) =~ "Connected Clients: 2"
end

test "handle_info/2 Presence Update - Leaver", %{conn: conn} do
  {:ok, view, html} = live(conn, "/")
  assert html =~ "Connected Clients: 1"
  send(view.pid, %{
    event: "presence_diff",
    payload: %{joins: %{},
                leaves: %{"phx-Fhb_dqdqsOCzKQAl" => %{metas: [%{phx_ref: "Fhb_dqdrwlCmfABl"}]}}}})
  assert render(view) =~ "Connected Clients: 0"
end

With those tests in place, re-running the tests with coverage mix c, you should see the following:

.........
Finished in 0.1 seconds (0.04s async, 0.1s sync)
9 tests, 0 failures

Randomized with seed 958121
----------------
COV    FILE                                        LINES RELEVANT   MISSED
100.0% lib/counter.ex                                  9        0        0
100.0% lib/counter/presence.ex                         5        0        0
100.0% lib/counter_web/components/layouts.ex           5        0        0
100.0% lib/counter_web/controllers/page_html.ex        5        0        0
100.0% lib/counter_web/endpoint.ex                    46        0        0
100.0% lib/counter_web/live/counter.ex                51       13        0
100.0% lib/counter_web/live/counter_component.e       17        2        0
100.0% lib/counter_web/live/counter_state.ex          53       12        0
100.0% lib/counter_web/live/presence_component.        9        2        0
[TOTAL] 100.0%
----------------

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!


What's Next?

If you've enjoyed this basic counter tutorial and want something a bit more advanced, checkout our LiveView Chat Tutorial: github.com/dwyl/phoenix-liveview-chat-example ๐Ÿ’ฌ
Then if you want a more advanced "real world" App that uses LiveView extensively including Authentication and some client-side JS, checkout our MVP App /dwyl/mvp ๐Ÿ“ฑโณโœ… โค๏ธ



Feedback ๐Ÿ’ฌ ๐Ÿ™

Several people in the Elixir / Phoenix community have found this tutorial helpful when starting to use LiveView, e.g: Kurt Mackey @mrkurt twitter.com/mrkurt/status/1362940036795219973

mrkurt-liveview-tweet

He deployed the counter app to a 17 region cluster using fly.io: https://liveview-counter.fly.dev

liveview-counter-cluster

Code: https://github.com/fly-apps/phoenix-liveview-cluster/blob/master/lib/counter_web/live/counter.ex

Your feedback is always very much welcome! ๐Ÿ™



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. Many updates have been made to LiveView setup since Dennis published his video, 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/

Relevant + Recommended Reading

phoenix-liveview-counter-tutorial's People

Contributors

ajmeese7 avatar arhell avatar asntc avatar bigtom avatar chargio avatar dependabot[bot] avatar ducdetronquito avatar elijose55 avatar iteles avatar ivymarkwell avatar jimjsong avatar luchoturtle avatar nelsonic avatar palerdot avatar pgrimaud avatar rabeagleissner avatar robstallion avatar sh41 avatar simonlab avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phoenix-liveview-counter-tutorial's Issues

Which pubsub?

This is just an open question. I believe that Phoenix ships three ways for real-time "pubsubing": Channels, Phoenix.PubSub and MyAppWeb.Endpoint. I imagine there are all abstractions above the same Phoenix.PubSub, but any guidance on how/why you would pick up one?

Chore: Tidy `README.md` Screenshots and Markdown Fails

Reading through the README.md at 3a8ae45 there are quite a few inconsistencies and Markdown fails

e.g: Old screenshot: https://github.com/dwyl/phoenix-liveview-counter-tutorial/tree/3a8ae4560fde21bfb138c0d064e7f24c9c19b51f#run-the-app
image

There are 11 instances of the `` (double-backtic) character:
image

This is because VSCodium was inserting double yesterday while I was trying to fix things ... ๐Ÿคฆโ€โ™‚๏ธ

Todo

  • Do a quick read-through of the README.md and all the code ๐Ÿ‘€
  • Fix all the inconsistencies ๐Ÿ“
  • Create PR ๐Ÿ†•

mix: FunctionClauseError: no function clause matching in String.to_charlist/1

mix fails to install tailwindcss and esbuild with empty proxy environment variables on nixos linux

workaround: unset http_proxy https_proxy sock_proxy

since im a complete noob in elixir, who is to blame here? mix?

nix-shell -p elixir_1_14 inotify-tools
elixir -v 
# Erlang/OTP 24 [erts-12.3.2.5] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [jit]
# Elixir 1.14.1 (compiled with Erlang/OTP 24)
mix local.hex
mix archive.install hex phx_new
mix phx.new -v
# Phoenix installer v1.6.15
git clone https://github.com/dwyl/phoenix-liveview-counter-tutorial --depth 1
cd phoenix-liveview-counter-tutorial
mix setup
mix phx.server

[info] Running LiveViewCounterWeb.Endpoint with cowboy 2.9.0 at 127.0.0.1:4000 (http)
[debug] Downloading tailwind from https://github.com/tailwindlabs/tailwindcss/releases/download/v3.1.8/tailwindcss-linux-x64
[debug] Using HTTP_PROXY: 
[debug] Downloading esbuild from https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.41.tgz
[debug] Using HTTP_PROXY: 
[info] Access LiveViewCounterWeb.Endpoint at http://localhost:4000
[error] Task #PID<0.494.0> started from LiveViewCounterWeb.Endpoint terminating
** (FunctionClauseError) no function clause matching in String.to_charlist/1
    (elixir 1.14.1) String.to_charlist(nil)
    (tailwind 0.1.9) lib/tailwind.ex:298: Tailwind.fetch_body!/1
    (tailwind 0.1.9) lib/tailwind.ex:230: Tailwind.install/0
    (tailwind 0.1.9) lib/tailwind.ex:215: Tailwind.install_and_run/2
    (phoenix 1.7.0-rc.1) lib/phoenix/endpoint/watcher.ex:19: Phoenix.Endpoint.Watcher.watch/2
    (elixir 1.14.1) lib/task/supervised.ex:89: Task.Supervised.invoke_mfa/2
    (stdlib 3.17.2.1) proc_lib.erl:226: :proc_lib.init_p_do_apply/3
Function: &Phoenix.Endpoint.Watcher.watch/2
    Args: ["tailwind", {Tailwind, :install_and_run, [:default, ["--watch"]]}]
[error] Task #PID<0.493.0> started from LiveViewCounterWeb.Endpoint terminating
** (FunctionClauseError) no function clause matching in String.to_charlist/1
    (elixir 1.14.1) String.to_charlist(nil)
    (esbuild 0.6.0) lib/esbuild.ex:353: Esbuild.httpc_proxy/1
    (esbuild 0.6.0) lib/esbuild.ex:312: Esbuild.fetch_body!/1
    (esbuild 0.6.0) lib/esbuild.ex:217: Esbuild.install/0
    (esbuild 0.6.0) lib/esbuild.ex:189: Esbuild.install_and_run/2
    (phoenix 1.7.0-rc.1) lib/phoenix/endpoint/watcher.ex:19: Phoenix.Endpoint.Watcher.watch/2
    (elixir 1.14.1) lib/task/supervised.ex:89: Task.Supervised.invoke_mfa/2
    (stdlib 3.17.2.1) proc_lib.erl:226: :proc_lib.init_p_do_apply/3
Function: &Phoenix.Endpoint.Watcher.watch/2
    Args: ["esbuild", {Esbuild, :install_and_run, [:default, ["--sourcemap=inline", "--watch"]]}]
[debug] Downloading tailwind from https://github.com/tailwindlabs/tailwindcss/releases/download/v3.1.8/tailwindcss-linux-x64
[debug] Using HTTP_PROXY: 
[debug] Downloading esbuild from https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.41.tgz
[debug] Using HTTP_PROXY: 
[error] Task #PID<0.495.0> started from LiveViewCounterWeb.Endpoint terminating
** (FunctionClauseError) no function clause matching in String.to_charlist/1
    (elixir 1.14.1) String.to_charlist(nil)
    (tailwind 0.1.9) lib/tailwind.ex:298: Tailwind.fetch_body!/1
    (tailwind 0.1.9) lib/tailwind.ex:230: Tailwind.install/0
    (tailwind 0.1.9) lib/tailwind.ex:215: Tailwind.install_and_run/2
    (phoenix 1.7.0-rc.1) lib/phoenix/endpoint/watcher.ex:19: Phoenix.Endpoint.Watcher.watch/2
    (elixir 1.14.1) lib/task/supervised.ex:89: Task.Supervised.invoke_mfa/2
    (stdlib 3.17.2.1) proc_lib.erl:226: :proc_lib.init_p_do_apply/3
Function: &Phoenix.Endpoint.Watcher.watch/2
    Args: ["tailwind", {Tailwind, :install_and_run, [:default, ["--watch"]]}]
[error] Task #PID<0.496.0> started from LiveViewCounterWeb.Endpoint terminating
** (FunctionClauseError) no function clause matching in String.to_charlist/1
    (elixir 1.14.1) String.to_charlist(nil)
    (esbuild 0.6.0) lib/esbuild.ex:353: Esbuild.httpc_proxy/1
    (esbuild 0.6.0) lib/esbuild.ex:312: Esbuild.fetch_body!/1
    (esbuild 0.6.0) lib/esbuild.ex:217: Esbuild.install/0
    (esbuild 0.6.0) lib/esbuild.ex:189: Esbuild.install_and_run/2
    (phoenix 1.7.0-rc.1) lib/phoenix/endpoint/watcher.ex:19: Phoenix.Endpoint.Watcher.watch/2
    (elixir 1.14.1) lib/task/supervised.ex:89: Task.Supervised.invoke_mfa/2
    (stdlib 3.17.2.1) proc_lib.erl:226: :proc_lib.init_p_do_apply/3
Function: &Phoenix.Endpoint.Watcher.watch/2
    Args: ["esbuild", {Esbuild, :install_and_run, [:default, ["--sourcemap=inline", "--watch"]]}]
[info] Running LiveViewCounterWeb.Endpoint with cowboy 2.9.0 at 127.0.0.1:4000 (http)
[info] Access LiveViewCounterWeb.Endpoint at http://localhost:4000
[debug] Downloading tailwind from https://github.com/tailwindlabs/tailwindcss/releases/download/v3.1.8/tailwindcss-linux-x64
[debug] Downloading esbuild from https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.41.tgz
[debug] Using HTTP_PROXY: 
[debug] Using HTTP_PROXY: 

lib/esbuild.ex:353

  defp httpc_proxy(proxy) do
    %{host: host, userinfo: userinfo, port: port} = URI.parse(proxy)
    authority = if userinfo, do: "#{userinfo}@#{host}", else: host
    {{String.to_charlist(authority), port}, []} # lib/esbuild.ex:353
  end

lib/tailwind.ex:298

  defp fetch_body!(url) do
    url = String.to_charlist(url)
    Logger.debug("Downloading tailwind from #{url}")

    {:ok, _} = Application.ensure_all_started(:inets)
    {:ok, _} = Application.ensure_all_started(:ssl)

    if proxy = System.get_env("HTTP_PROXY") || System.get_env("http_proxy") do
      Logger.debug("Using HTTP_PROXY: #{proxy}")
      %{host: host, port: port} = URI.parse(proxy)
      :httpc.set_options([{:proxy, {{String.to_charlist(host), port}, []}}]) # lib/tailwind.ex:298
    end

System.get_env("http_proxy") is empty string, but truthy

env | grep -i proxy

https_proxy=
sock_proxy=
http_proxy=

workaround

unset http_proxy https_proxy sock_proxy
env | grep -i proxy | wc -l

0
mix phx.server

[info] Running LiveViewCounterWeb.Endpoint with cowboy 2.9.0 at 127.0.0.1:4000 (http)
[debug] Downloading tailwind from https://github.com/tailwindlabs/tailwindcss/releases/download/v3.1.8/tailwindcss-linux-x64
[debug] Downloading esbuild from https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.41.tgz
[info] Access LiveViewCounterWeb.Endpoint at http://localhost:4000
[watch] build finished, watching for changes...

Learning components

Nice job! I wrote this for myself, nothing glorious, just notes with a different perspective, which I expect to be correct. To push things further and follow you, refactor this with a GenServer for the "business logic", make it real-time and use Presence!

cd into app folder before running the tests

Given this is a tutorial for complete beginners, as stated in the intro, it might be worth adding a note to 'Checkpoint 1: Run the Tests!' that you need to cd into the app folder before running them.

If you type mix test into the CLI straight after installing the dependencies you'll get:
image

Phoenix is very user-friendly in that it gives you hints straight away if you wanted to run your new app:
image
But if you're brand new to phoenix (and programming), you might miss it.

In your terminal, go into the newly created app folder using:

cd live_view_counter

Why does using handle_call mean the calling LiveView will be updated twice?

In the Moving State Out of LiveViews section, there is a note stating: 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.

Why will the LiveView be updated twice?

I put an IO.inspect() in the render function of LiveViewCounterWeb.Counter liveview to verify that it only gets called once. However, I may be misunderstanding something:

defmodule LiveViewCounterWeb.Counter do

...

def render(assigns) do
    IO.inspect(binding(), label: "RENDER")

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

...

end

Upon incrementing the counter once, the following is printed:

RENDER: [
  assigns: %{
    __changed__: %{val: true},
    flash: %{},
    live_action: nil,
    socket: #Phoenix.LiveView.Socket<
      assigns: #Phoenix.LiveView.Socket.AssignsNotInSocket<>,
      endpoint: LiveViewCounterWeb.Endpoint,
      id: "phx-FwamoEC_wHbX5AHk",
      parent_pid: nil,
      root_pid: #PID<0.529.0>,
      router: LiveViewCounterWeb.Router,
      transport_pid: #PID<0.523.0>,
      view: LiveViewCounterWeb.Counter,
      ...
    >,
    val: 0
  }
]

Broken link for server hanging section

The link in Step 1 to the troubleshooting section for the server hanging is broken.

It needs to be amended from try [this](###-problems-with-dependencies) to try [updating your deps as explained in our troubleshooting section](#problems-getting-the-initial-server-running)

Heroku Build/Deploy Fails

Deploy build fails:
image

** (Mix) You're trying to run :live_view_counter on Elixir v1.9.1 but it has declared in its mix.exs file it supports only Elixir ~> 1.10
 !     Push rejected, failed to compile Elixir app.
 !     Push failed

image

Todo

Initial render renders without styling

Hello!

I was recently using your tutorial to update my own application of LiveView because I had found this issue #5 you had opened and was having the same problem.

I noticed that the initial render of the application was still rendering without the styling the exact same way and I believe it is because the root layout is defined as a LiveView layout. Reading the documentation, I believe defining the root layout as a LiveView layout is preventing the initial render to include the styling since the LiveView layouts are rendered after (?), the same way as the initial problem (except before they were never being rendered). I've attached a couple of gifs to better illustrate.

Before:
before

After:
after

I fixed this in my own repo by defining the root layout in the router, like:

live "/dashboard", MyApp.Dashboard, layout: {MyApp.LayoutView, :root}

and rendering the root layout as a regular .eex template. I also of course pulled down y'all's repo and verified this also fixes the same problem. Anyways! I know it's a super minute issue, just wanted to point it out and also to clarify my own understanding of why the problem was happening.

Thanks :)

Update to phoenix_live_view 0.9.0

phoenix_live_view 0.9.0 was released two days ago: https://hex.pm/packages/phoenix_live_view
I've attempted to update to 0.9.0 but it breaks:
image

For reference, this is what it should look like:
phoenix-liveview-counter-single-windowl

view-source:http://localhost:4000 suggests that the layout template is not being rendered:
image

Todo

  • Investigate why the layout is not being rendered!

Images/assets not loading when running the finished app on my localhost (step 0)

Not stuck, just a weird detail I found :)
As title says. When running the app locally I see this:

image

And this:

daniel@debian ~/c/phoenix-liveview-counter-tutorial (main)> mix phx.server
[info] Running CounterWeb.Endpoint with cowboy 2.10.0 at 127.0.0.1:4000 (http)
[info] Access CounterWeb.Endpoint at http://localhost:4000
[watch] build finished, watching for changes...

Rebuilding...

Done in 278ms.
[info] CONNECTED TO Phoenix.LiveView.Socket in 22ยตs
  Transport: :websocket
  Serializer: Phoenix.Socket.V2.JSONSerializer
  Parameters: %{"_csrf_token" => "a0IbDUJ0OEQkP3kadi8pKF4yGxwpBhNQXoQuuYwrKWOV5pdOnfxfD4u7", "_live_referer" => "undefined", "_mounts" => "0", "_track_static" => %{"0" => "http://localhost:4000/assets/app.css", "1" => "http://localhost:4000/assets/app.js"}, "vsn" => "2.0.0"}
[debug] MOUNT CounterWeb.Counter
  Parameters: %{}
  Session: %{"_csrf_token" => "3-Jx7-O6oh6LC_Mg0Tczm2fg"}
[debug] Replied in 3ms
[info] GET /
[debug] Processing with CounterWeb.Counter.Elixir.CounterWeb.Counter/2
  Parameters: %{}
  Pipelines: [:browser]
[info] Sent 200 in 18ms
[info] CONNECTED TO Phoenix.LiveView.Socket in 23ยตs
  Transport: :websocket
  Serializer: Phoenix.Socket.V2.JSONSerializer
  Parameters: %{"_csrf_token" => "a0IbDUJ0OEQkP3kadi8pKF4yGxwpBhNQXoQuuYwrKWOV5pdOnfxfD4u7", "_live_referer" => "undefined", "_mounts" => "1", "_track_static" => %{"0" => "http://localhost:4000/assets/app.css", "1" => "http://localhost:4000/assets/app.js"}, "vsn" => "2.0.0"}
[info] GET /images/logo.svg
[debug] ** (Phoenix.Router.NoRouteError) no route found for GET /images/logo.svg (CounterWeb.Router)
    (counter 1.7.7) lib/phoenix/router.ex:489: CounterWeb.Router.call/2
    (counter 1.7.7) lib/counter_web/endpoint.ex:1: CounterWeb.Endpoint.plug_builder_call/2
    (counter 1.7.7) lib/plug/debugger.ex:136: CounterWeb.Endpoint."call (overridable 3)"/2
    (counter 1.7.7) lib/counter_web/endpoint.ex:1: CounterWeb.Endpoint.call/2
    (phoenix 1.7.10) lib/phoenix/endpoint/sync_code_reload_plug.ex:22: Phoenix.Endpoint.SyncCodeReloadPlug.do_call/4
    (plug_cowboy 2.6.1) lib/plug/cowboy/handler.ex:11: Plug.Cowboy.Handler.init/2
    (cowboy 2.10.0) /home/daniel/code/phoenix-liveview-counter-tutorial/deps/cowboy/src/cowboy_handler.erl:37: :cowboy_handler.execute/2
    (cowboy 2.10.0) /home/daniel/code/phoenix-liveview-counter-tutorial/deps/cowboy/src/cowboy_stream_h.erl:306: :cowboy_stream_h.execute/3
    (cowboy 2.10.0) /home/daniel/code/phoenix-liveview-counter-tutorial/deps/cowboy/src/cowboy_stream_h.erl:295: :cowboy_stream_h.request_process/3
    (stdlib 4.2) proc_lib.erl:240: :proc_lib.init_p_do_apply/3

[info] CONNECTED TO Phoenix.LiveView.Socket in 21ยตs
  Transport: :websocket
  Serializer: Phoenix.Socket.V2.JSONSerializer
  Parameters: %{"_csrf_token" => "QV4FD10ZEFwbOHEKHDUPFWc_JUJaVBNXrsOwj4_jtPGF_jBrWkF87fu0", "_live_referer" => "undefined", "_mounts" => "0", "_track_static" => %{"0" => "http://localhost:4000/assets/app.css", "1" => "http://localhost:4000/assets/app.js"}, "vsn" => "2.0.0"}
[debug] MOUNT CounterWeb.Counter
  Parameters: %{}
  Session: %{"_csrf_token" => "3-Jx7-O6oh6LC_Mg0Tczm2fg"}
[debug] Replied in 189ยตs

Some info about my system:

daniel@debian ~/c/phoenix-liveview-counter-tutorial (main)> neofetch
       _,met$$$$$gg.          daniel@debian
    ,g$$$$$$$$$$$$$$$P.       -------------
  ,g$$P"     """Y$$.".        OS: Debian GNU/Linux 12 (bookworm) x86_64
 ,$$P'              `$$$.     Host: Swift SFX14-41G V1.10
',$$P       ,ggs.     `$$b:   Kernel: 6.1.0-16-amd64
`d$$'     ,$P"'   .    $$$    Uptime: 4 hours, 8 mins
 $$P      d$'     ,    $$P    Packages: 1210 (dpkg), 22 (brew)
 $$:      $$.   -    ,d$$'    Shell: bash 5.2.15
 $$;      Y$b._   _,d$P'      Resolution: 1920x1080
 Y$$.    `.`"Y$$$$P"'         WM: i3
 `$$b      "-.__              Terminal: tmux
  `Y$$                        CPU: AMD Ryzen 7 5800U with Radeon Graphics (16) @ 1.900GHz
   `Y$$.                      GPU: AMD ATI Radeon Vega Series / Radeon Vega Mobile Series
     `$$b.                    GPU: NVIDIA GeForce RTX 3050 Ti Mobile
       `Y$$b.                 Memory: 1964MiB / 15337MiB
          `"Y$b._
              `"""
daniel@debian ~/c/phoenix-liveview-counter-tutorial (main)> elixir -v
Erlang/OTP 25 [erts-13.1.5] [source] [64-bit] [smp:16:16] [ds:16:16:10] [async-threads:1] [jit:ns]

Elixir 1.14.0 (compiled with Erlang/OTP 24)
daniel@debian ~/c/phoenix-liveview-counter-tutorial (main)> mix phx.new -v
Phoenix installer v1.7.10

2022 Update

Trying to follow this tutorial from scratch with latest Elixir, Erlang/OTP & Phoenix and getting the following error:

n@MBP live_view_counter % mix phx.server
=ERROR REPORT==== 28-May-2022::23:07:54.595746 ===
beam/beam_load.c(551): Error loading function rebar3:parse_args/1: op put_tuple u x:
  please re-compile this module with an Erlang/OTP 25 compiler

escript: exception error: undefined function rebar3:main/1
  in function  escript:run/2 (escript.erl, line 750)
  in call from escript:start/1 (escript.erl, line 277)
  in call from init:start_em/1
  in call from init:do_boot/3
** (Mix) Could not compile dependency :telemetry, "/Users/n/.mix/rebar3 bare compile --paths /Users/n/code/temp/live_view_counter/_build/dev/lib/*/ebin" command failed. Errors may have been logged above. You can recompile this dependency with "mix deps.compile telemetry", update it with "mix deps.update telemetry" or clean it with "mix deps.clean telemetry"

The project's URL leads to a non-existent Heroku app

The URL associated with this project is https://live-view-counter.herokuapp.com/ but the app does not exist.

Todo

  • Create new Fly.io Org with debit card attached. ๐Ÿ†• โณ ๐Ÿ’ณ
  • Prep project with necessary files to deploy ๐Ÿง‘โ€๐Ÿ’ป
  • Deploy to Fly.io ๐Ÿš€
  • Update Screenshot (GIF) in README.md:
    <div>
    <a href="https://live-view-counter.herokuapp.com/">
    <img src="https://user-images.githubusercontent.com/194400/76150696-2e3f6b80-60a5-11ea-8d65-1999a70bb40a.gif">
    </a>
    </div>

Opening an issue to be closed :)

I would like to have a repo that demonstrates "live navigation" because it is not at all obvious. The Liveview API is still quite unstable. Would you like to create a repo and I would push a demo repo? It would be navigation between liveviews, and navigation between LiveComponents (children of the main liveview). I would then like to (for example) stream data into a page to demonstrate how to pass data between livecomponents, and between liveviews.

I made an example: https://github.com/ndrean/navigation-liveviews-livecomponents

npm install --prefix assets error on windows 10

\Projects\elixir\phoenix>elixir -v
Erlang/OTP 21 [erts-10.3] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1]

Elixir 1.10.2 (compiled with Erlang/OTP 21)

\Projects\elixir\phoenix>mix phx.new -v
Phoenix v1.4.15

\Projects\elixir\phoenix>node -v
v12.16.1

after cloning and mix deps.get successfully I attempt
npm install --prefix assets
and I get
\Projects\elixir\phoenix\phoenix-liveview-counter-tutorial>npm install --prefix assets
npm ERR! code ENOLOCAL
npm ERR! Could not install from "" as it does not contain a package.json file.

npm ERR! A complete log of this run can be found in:
npm ERR!
\AppData\Roaming\npm-cache_logs\2020-03-12T16_40_00_067Z-debug.log

2020-03-12T16_40_00_067Z-debug.log

`Moving state out of the LiveViews` counter.ex missing diff

That last lib/live_view_counter_web/live/counter.ex is missing this diff:

    use Phoenix.LiveView
    alias LiveViewCounter.Count
    alias Phoenix.PubSub
+   alias LiveViewCounter.Presence

    @topic Count.topic
+   @presence_topic "presence"

    def mount(_params, _session, socket) do

5.1 Update the Failing Test Assertion - different test code with Phoenix v1.6.2

$ mix test
Compiling 16 files (.ex)
Generated live_view_counter app
..

  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<meta content=\"fgAsKnBOHDokdCQkL2t-K3QGEysjP3BZ39Aa5zjKeGWrn3GsCGatjU6l\" name=\"csrf-token\">\n<title data-suffix=\" ยท Phoenix Framework\">LiveViewCounter ยท Phoenix Framework</title>\n    <link phx-track-static rel=\"stylesheet\" href=\"/assets/app.css\">\n    <script defer phx-track-static type=\"text/javascript\" src=\"/assets/app.js\"></script>\n  </head>\n  <body>\n    <header>\n      <section class=\"container\">\n        <nav>\n          <ul>\n            <li><a href=\"https://hexdocs.pm/phoenix/overview.html\">Get Started</a></li>\n\n              <li><a href=\"/dashboard\">LiveDashboard</a></li>\n\n          </ul>\n        </nav>\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<div data-phx-main=\"true\" data-phx-session=\"SFMyNTY.g2gDaAJhBXQAAAAIZAACaWRtAAAAFHBoeC1GckFqTnUyaVdjalJRd0JvZAAMbGl2ZV9zZXNzaW9uaAJkAAdkZWZhdWx0bggAvLhT0DYjsBZkAApwYXJlbnRfcGlkZAADbmlsZAAIcm9vdF9waWRkAANuaWxkAAlyb290X3ZpZXdkACFFbGl4aXIuTGl2ZVZpZXdDb3VudGVyV2ViLkNvdW50ZXJkAAZyb3V0ZXJkACBFbGl4aXIuTGl2ZVZpZXdDb3VudGVyV2ViLlJvdXRlcmQAB3Nlc3Npb250AAAAAGQABHZpZXdkACFFbGl4aXIuTGl2ZVZpZXdDb3VudGVyV2ViLkNvdW50ZXJuBgCH22CkfAFiAAFRgA.lzuLa_S8yB9-tbbF0q53E37aZcgrXqJ6_9loIWCoj_A\" data-phx-static=\"SFMyNTY.g2gDaAJhBXQAAAADZAAKYXNzaWduX25ld2pkAAVmbGFzaHQAAAAAZAACaWRtAAAAFHBoeC1GckFqTnUyaVdjalJRd0JvbgYAi9tgpHwBYgABUYA.c8ytqgr0rYOYyw-Q1b5bMKoVfSPuBeKkC3eC3Oep1Zw\" id=\"phx-FrAjNu2iWcjRQwBo\"><div>\n  <h1>The count is: 0</h1>\n  <button phx-click=\"dec\">-</button>\n  <button phx-click=\"inc\">+</button>\n</div>\n</div>\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.04 seconds (0.02s async, 0.02s sync)
3 tests, 1 failure

Randomized with seed 500082

The fix needs to be updated.

Feat: Split `counter.ex` into a basic `LiveView` Component

At present the counter.ex file contains the following render function:

def render(assigns) do
~H"""
<div>
<h1 class="text-4xl font-bold text-center"> The count is: <%= @val %> </h1>
<p class="text-center">
<.button phx-click="dec">-</.button>
<.button phx-click="inc">+</.button>
</p>
<h1 class="text-4xl font-bold text-center"> Current users: <%= @present %></h1>
</div>
"""
end

Todo

  • Split this out into it's own LiveView Component

  • Also tidy this appearance:

image

Please Note: there's no urgent need to do this work ...
The reason I'm doing this split here in the counter (the simplest possible LiveView app)
is so that I can learn how LiveView Components work from first principals for: dwyl/mvp#141 (comment)

Distributed version

Today, I made the distributed version of this as your link is dead. This means you run each app on a different port and cluster them and everything works. I plan to test the deployment on Fly.io. Some interest to publish this as a branch?

Screenshot 2023-10-28 at 21 11 36

https://github.com/ndrean/elixir-hiring-project/tree/updated-version

They (Fly.io) say it is a 2h job. Really? For example, counting twice some events: the proposed code is wrong. And not totally straightforward to sync all the views when a user leaves... Took me the day to make it workn and just on time for the rugby!

Finished project broken

The finished project does not work on my machine (Debian 10). After entering mix phx.server I was prompted to install rebar3, which I did. Entering mix phx.server gets me this error:

function :crypto.hmac/3 is undefined or private 

immediate interaction with new window overrides existing windows' values

To reproduce: open the heroku counter in a browser window, increment it a few times. Open the same counter in another browser window. It will display 0 rather than the value from the first window.

If you:

A) increment the first window's counter again, and the other window will pick it up and then both will interact as expected.

B) increment the second window's counter from 0 to 1 or -1 and it will overwrite whatever value was in the first window with that as well.

Both the initial display of 0 in the second window and the overriding of the first window's count with the second's in the "B" case seem like bugs.

Switch step 4 and step 5?

If we update the endpoint.ex file before the router.ex file we won't need to add

import Phoenix.LiveView.Router

in the router file as it will already be imported automatically with the new change from the endoint file:

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

Mac-only error: Can't find executable `mac-listener`

This error may not be specific to the liveview counter tutorial but I wanted to leave a note here in case anyone else comes across it.

My server was hanging in Step 1, but it wasn't throwing the error mentioned in https://github.com/dwyl/phoenix-liveview-counter-tutorial#problems-getting-the-initial-server-running
It was however throwing this error:
image

At this stage, I don't know if this will fix the server hanging issue but it's an error that would be useful to be fixed either way.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.