Hi @IwateKyle, I’m sorry to hear that you found this particular exercise so challenging. Rest assured that live_patch
is covered in greater detailed later on in the book and we will update the text to let readers know.
In the meantime, here is some guidance on the solution:
- Per the docs here (and as shown in the original question on this thread above), you can write the
live_patch
function call in the markup in therender
function ofWrongLive
like this:
<%= live_patch to: Routes.live_path(@socket, __MODULE__), replace: true do %>
<button>Try again!</button>
<%end%>
This adds a button that is wrapped in a special kind of link called a “live patch”. A “live patch” link basically re-directs to the current live view without reloading it. From the docs, if you call live_patch
with the route to the current live view…
…the new state is pushed to the client, without reloading the whole page while also maintaining the current scroll position
The value of the :to
key in the argument to live_patch
can be any route. To specify the route of the current live view, you use: Routes.live_path(@socket, __MODULE__)
or you could use Routes.live_path(@socket, PentoWeb.WrongLive)
, which evaluates to the same thing. The third example in the docs here is accurate https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.Helpers.html#live_patch/2-examples.
To fully get this working, you need to add this live_patch
link I described above, and you need to implement a new function in your live view, a handle_params/3
function. From the docs:
When navigating to the current LiveView,
Phoenix.LiveView.handle_params/3
is immediately invoked to handle the change of params and URL state.
If you follow the link to the handle_params/3
docs, you will see that it takes in three arguments: some params, the URI and the socket, and it needs to return {:noreply, socket}
. If we are aiming to “reset” the game, then we should return a socket with the appropriate starting state. So something like this:
def handle_params(_params, _uri, socket) do
{
:noreply,
assign(
socket,
score: 0,
message: "Guess a number."
)
}
end
That should do it! I hope this helps and thanks very much for your feedback.