So I started learning Channels yesterday, and am somewhat lost.
https://hexdocs.pm/phoenix/channels.html
let room = 1
let channel = socket.channel(`room: ${room}`, {})
I know I can do the above and pass a value or values to the JS to change the room number, but is it possible to do so server side instead?
I’m struggling to figure out or find information on how you could create a handle_event which sets the room value, and then pass it directly to the channel. Is it possible to call the join function within a handle_event? If so how is it done?
I have a handle_event that can set the room number, but channels seem to have empty assigns by default.
@impl true
def join("room:" <> room_id, _params, socket) do
room_id = .....
{:ok, socket}
end
Hey there,
have you already been successful? Otherwise I would point you towards the assign/3
function of the Socket module. [1]
Looking at your join function it’s already the point where you can assign the room_id
to your connection (the socket) and make it available throughout the whole lifetime of the connection. Like so:
@impl true
def join("room:" <> room_id, _params, socket) do
socket = assign(socket, :room_id, room_id
{:ok, socket}
end
And later with channel events when you use the handle_in/3
callbacks you can identify the room_id again by getting the room_id value assigned to the socket. like so:
def handle_in("ping", payload, socket) do
# keep in mind it's just a simple map of atom keys and dot notation can be used but is not a must ;-)
room_id = socket.assigns.room_id
# do something
{:reply, {:ok, room_id}, socket}
end
Hope that helps for your understanding of the mechanism?!
[1] Phoenix.Socket — Phoenix v1.7.2