socket is being accessed in the function body, hence the need to include it in the function head.
Current:
def maybe_track_user(
-
product,*
-
%{assigns: %{live_action: :show, user_token: user_token}}*
-
) do*
-
if connected?(socket) do*
-
user = Accounts.get_user_by_session_token(user_token)*
-
# do tracking here!*
- end*
Expected:
def maybe_track_user(
-
product,*
-
%{assigns: %{live_action: :show, user_token: user_token}} **= socket***
-
) do*
-
if connected?(socket) do*
-
user = Accounts.get_user_by_session_token(user_token)*
-
# do tracking here!*
end
Title: Programming Phoenix LiveView: B3.0: Include “=socket” in function header (page 255)
Example: Programming Flutter - ‘pub get’ command not working (page 15)
Please also add the book’s tag if it has not already present, thanks!
Thanks for pointing this out! You’ll find the correction in the next Beta release
Programming Phoenix LiveView
Hello,
I am reading my way through the book, Programming Phoenix LiveView, and in chapter 9 (B3.0): Distributed Dashboard, and specifically on the use of Phoenix.Presence; you used a case to check whether the presence has the specified key in its store. However, the case options you use is an empty list and a map.
case Presence.get_by_key(“user_activity”, product.name) do
[] →
Presence.track(
pid,
“user_activity”,
product.name, %{users: [%{email: user.email}]}
)
%{users: active_users_for_product} ->
Presence.update(pid, "user_activity", product.name, %{
users: [active_users_for_product | %{email: user.email}]
})
end
However, every time I try this, i get “** (CaseClauseError) no case clause matching: %{metas: [%{phx_ref: “FnKY8Tohq2e74wJj”, users: [%{email: “okari@gmail.com”}]}]}”.
Checking it’s documentation also reveals the return type for the function is a map ( presences() ). I might be missing something but I would appreciate your help understanding this, and Presence in general as well as your insights in Phoenix.
Kind regards,
Frankline Okari
okarifrankline5678@gmail.com
Hi! Thanks for submitting your question. It does in fact look like there is a mistake in that code! The correct case
statement should read like this:
case Presence.get_by_key("user_activity", product.name) do
[] ->
Presence.track(
pid,
"user_activity",
product.name, %{users: [%{email: user.email}]}
)
%{metas: [%{users: active_users_for_product}]} ->
Presence.update(pid, "user_activity", product.name, %{
users: [active_users_for_product | %{email: user.email}]
})
end
You’ll find that updated in the next Beta release. In the meantime, you can copy in the correction from this comment.