Programming Phoenix LiveView (PragProg)

This is the code I wrote in the first chapter’s your turn section which doesn’t work. What am I missing?

defmodule PentoWeb.WrongLive do
  use Phoenix.LiveView, layout: {PentoWeb.LayoutView, "live.html"}

  def mount(_params, _session, socket) do
    {:ok, assign(socket, score: 0, message: "Make a guess", rand_num: :rand.uniform(10))}
  end

  def render(assigns) do
    ~H"""
    <h1>Your score: <%= @score %></h1>
    <h2>
      <%= @message %>
      <br>
      It's <%= time() %>
    </h2>
    <h2>
      <%= for n <- 1..10 do %>
        <a href="#" phx-click="guess" phx-value-number={n}><%= n %></a>
      <% end %>
    </h2>
    """
  end

  def time() do
    DateTime.utc_now() |> to_string()
  end

  def handle_event("guess", %{"number" => guess}=_data, socket) do

    cond do
      guess == socket.assigns.rand_num ->
        message = "Your guess: #{guess}. You won! :)"
        {
          :noreply,
          assign(
            socket,
            message: message
          )
        }

      true ->
        message = "Your guess: #{guess}. Wrong. Guess again."
        score = socket.assigns.score - 1
        {
          :noreply,
          assign(
            socket,
            message: message,
            score: score
          )
        }
    end

  end
end

Question # 2, (not related to LiveView, but Elixir)

Why it doesn’t compile when I write

{
  :noreply,
  assign(
    socket,
    message: message,
    score: score
   )
  }

outside the cond?
The compilation error is:

** (CompileError) lib/pento_web/live/wrong_live.ex:44: undefined function message/0 (expected PentoWeb.WrongLive to define such a function or for it to be imported, but none are available)


Question # 3:
Are the solutions to the exercises available somewhere?

@SophieDeBenedetto

I’m still waiting…
Will somebody please reply my question?

What does that describe for you? Follow that path.
Sorry its just not fresh in my head, but trying to read the error this is what its telling me.

@pillaiindu
In your handle_event function, the comparison
guess == socket.assigns.rand_num
is comparing a string (‘guess’) with an integer, which won’t work. The answer will be to convert guess to an int before making the comparison.

The simplest way to investigate the problem would have been to IO.inspect your guess and random number values before the comparison. That’s often a good first troubleshooting approach - sanity check what values you’re dealing with.

On your Q 2 - I agree that particular compiler message isn’t the most helpful, but with a bit of Elixir practise you’ll see it often enough to recognise in future. Here it just means the compiler doesn’t know about the message variable. You define it in the cond, so it doesn’t exist outside of that scope. The compiler tries to interpret it as a 0-arity function, which it can’t find. It would have the same problem with sort, but doesn’t get that far before erroring.

[btw - your 2nd question is the pattern to follow as in that one you are nicely specific about the error. That kind of context really helps someone trying to answer]

1 Like

Thank you!

I will use your suggestions and see how it goes.

Yes, that was the problem.
Adding {guess_num, _} = Integer.parse(guess) and then comparing guess_num instead of guess worked. :slight_smile:

But I still don’t know if the code I wrote is beautiful and idiomatic or not.

Thank you!

IO.inspect is great advice. I was very confused when using IO.puts - it showed both numbers were the same, and didn’t indicate their types.

Does anyone know which version of LiveView is used in the updated B8.0 version of the book, published a week ago?

1 Like

From the source code of the site it seems to be 0.17.5 for liveview and 1.6.2 for Phoenix.

5 Likes

Any idea when we can expect a new beta that covers LV 0.18+ along with Phoenix 1.7?

4 Likes

One of the authors, Sophie DeBenedetto, mentioned near the end of January that book’s next update will be at the end of February.

3 Likes

Heads up

2 Likes

Any info?

Not sure about another update (currently B8), but I’m pretty Sophie said the P1 (production release) of the book will be after we have LiveView hits 1.0, which will be in quite some time to be honest (which is understandable to be fair).

Any update?

The book’s co-author has revealed that a new version of the book is almost there, and it will likely be available very shortly (possibily next week). This new version will also include coverage of Phoenix 1.7, which is fantastic news for anyone interested in learning about this technology!

7 Likes

On product site:

Releases:

  • B9.0 2023/03/21
3 Likes

From PragProg email:

B9.0 Updates include:

This rewrite is our most extensive to date. Most of the changes are based on the new features in components, heex, tailwind.css, and generators.

  • Updated code to use recent versions of LiveView (0.18.x) and Phoenix (1.7).
  • Updated relevant chapters to reflect changes in these recent versions.
  • Updated chapters to use new calling style (HTML-style arguments passed into a single assigns attribute, and attr keywords.).
  • Added some basic tailwind discussion
  • Added Tailwind discussion, and used CoreComponents where possible.
  • Updated discussion on file uploads.
  • Updated code and prose with new included phx.auth.gen generators for liveview
  • Updated discussion on on_mount and live_session
  • Updates for verified routes and navigation
  • JavaScript client side events/hooks/scripts
  • Addressed errata.
11 Likes

Just purchased the book, thrilled to have it, thank you so much!

1 Like

A spotlight on @SophieDeBenedetto has just gone live on Devtalk!

Comment or ask a question in it to get a chance to win a copy of her book :023:

2 Likes