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?