feat: use link patch to navigate between rooms
Also, implement `c:handle_params/3` to allow the usage of `link patch`.
This commit is contained in:
parent
e20857f1d6
commit
fb7dff1f6f
@ -5,6 +5,7 @@ defmodule SlaxWeb.ChatRoomLive do
|
||||
alias Slax.Repo
|
||||
alias Slax.Chat.Room
|
||||
|
||||
@impl Phoenix.LiveView
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<div class="flex flex-col flex-shrink-0 w-64 bg-slate-100">
|
||||
@ -39,20 +40,28 @@ defmodule SlaxWeb.ChatRoomLive do
|
||||
"""
|
||||
end
|
||||
|
||||
def mount(params, _session, socket) do
|
||||
[room | _] = rooms = Repo.all(Room)
|
||||
@impl Phoenix.LiveView
|
||||
def mount(_params, _session, socket) do
|
||||
rooms = Repo.all(Room)
|
||||
|
||||
# NOTE: (jpd) on the lesson **15 path params and routes** the author makes a new call to the database. I changed
|
||||
# this behaviour and fetch the room from the list.
|
||||
room =
|
||||
Enum.find(
|
||||
rooms,
|
||||
&(Integer.to_string(&1.id) == Map.get(params, "id", Integer.to_string(room.id)))
|
||||
)
|
||||
|
||||
{:ok, assign(socket, hide_topic?: false, room: room, rooms: rooms)}
|
||||
{:ok, assign(socket, hide_topic?: false, rooms: rooms)}
|
||||
end
|
||||
|
||||
@impl Phoenix.LiveView
|
||||
def handle_params(params, _session, socket) do
|
||||
room =
|
||||
case Map.fetch(params, "id") do
|
||||
{:ok, id} ->
|
||||
Repo.get(Room, id)
|
||||
|
||||
:error ->
|
||||
List.first(socket.assigns.rooms)
|
||||
end
|
||||
|
||||
{:noreply, assign(socket, hide_topic?: false, room: room)}
|
||||
end
|
||||
|
||||
@impl Phoenix.LiveView
|
||||
def handle_event("toggle-topic", _params, socket) do
|
||||
{:noreply, update(socket, :hide_topic?, &(!&1))}
|
||||
end
|
||||
@ -60,20 +69,21 @@ defmodule SlaxWeb.ChatRoomLive do
|
||||
attr :active, :boolean, required: true
|
||||
attr :room, Room, required: true
|
||||
|
||||
@spec room_link(Phoenix.LiveView.Socket.assigns()) :: Phoenix.LiveView.Rendered.t()
|
||||
defp room_link(assigns) do
|
||||
~H"""
|
||||
<a
|
||||
<.link
|
||||
class={[
|
||||
"flex items-center h-8 text-sm pl-8 pr-3",
|
||||
(@active && "bg-slate-300") || "hover:bg-slate-300"
|
||||
]}
|
||||
href={~p"/rooms/#{@room}"}
|
||||
patch={~p"/rooms/#{@room}"}
|
||||
>
|
||||
<.icon name="hero-hashtag" class="h-4 w-4" />
|
||||
<span class={["ml-2 leading-none", @active && "font-bold"]}>
|
||||
<%= @room.name %>
|
||||
</span>
|
||||
</a>
|
||||
</.link>
|
||||
"""
|
||||
end
|
||||
end
|
||||
|
Loading…
x
Reference in New Issue
Block a user