flp
August 20, 2019, 6:34pm
1
I pretty much followed the docs about phoenix presence , but I cannot get it working in the UI. It works in the Elixir Code, but the info is never brought to the template.
Specifically, the onSync-Call seems never to be executed regardless the join of a new user :
presence.onSync(() => showOnlineStatus(presence))
If I do it manually as stated in the generated presence.ex
via
chatChannel.on("presence_diff", diff => {
showOnlineStatus(presence)
})
it calls the showOnlineStatus() function. Nevertheless,
presence.list((name, { metas: [first, ...rest] }) => { ... })
never executes anything, even though presence
contains the diff information.
The full code can be found in the Github repo .
What I am doing wrong? Do I miss anything what the docs requires me to do but isn’t stated? Are the docs missing anything?
2 Likes
I’m not sure if this is the issue but it looks like you are executing Presence.track
inside handle_in
instead of a handle_info:
use ChannelLiveViewDemoWeb, :channel
alias ChannelLiveViewDemoWeb.Presence
def join("chat", _payload, socket) do
{:ok, socket}
end
def handle_in("new_message", %{"sender" => sender, "message" => message}, socket) do
# Message.create sender_id, receiver_id, message
Presence.track(socket, sender, %{online_at: System.system_time(:second)})
push socket, "online", Presence.list(socket)
socket.endpoint.broadcast! "chat", "new_message", %{sender: sender, message: message}
{:noreply, socket}
end
end
Maybe it’ll work if you use send(self(), :after_join)
, here’s an example from the Phoenix.Presence docs:
def join("some:topic", _params, socket) do
send(self(), :after_join)
{:ok, assign(socket, :user_id, ...)}
end
def handle_info(:after_join, socket) do
push(socket, "presence_state", Presence.list(socket))
{:ok, _} = Presence.track(socket, socket.assigns.user_id, %{
online_at: inspect(System.system_time(:second))
})
{:noreply, socket}
end
1 Like
flp
August 21, 2019, 6:12am
3
Does not matter where it’s executed. I had it initially in a handle_info
but it also didn’t work.
If I follow this guide it works anyway. I still wonder, why the solution of the docs does not work.
That guide is for an older version of Phoenix. Have you seen something that works with 1.4?
Same exact issue for me, did anyone figure this out?
flp
May 23, 2020, 5:39pm
6
It might be for an older version but the guide definitely works for me with 1.4
1 Like
flp
June 7, 2020, 1:26pm
7
I figured out my problem but I cannot tell why I did that mistake, maybe the docs weren’t right at that time.
push socket, "online", Presence.list(socket)
was the problem. "online"
needs to match the callbacks you’re listening on with Javascript so there should have been "presence_state"
instead.
1 Like