Why are the socket assigns reset in `update/2` callback of LiveComponent?

I tried to unsubscribe old channel and to subscribe new channel in LiveComponent.
I expected that old channel is in the assigns of socket in update/2 callback of LiveComponent, but it isn’t.
All assigns of socket don’t exist.

  @impl true
  def update(assigns, socket) do
    old_channel_name = socket.assigns[:channel_name]
    new_channel_name = assigns.channel_name

    IO.inspect(socket.assigns, label: "socket.assigns")
    IO.inspect({old_channel_name, new_channel_name}, label: "assigns")

    if connected?(socket) do
      if old_channel_name do
        :ok = Chat.unsubscribe_channel(old_channel_name)
      end

      :ok = Chat.subscribe_channel(new_channel_name)
    end

    socket =
      socket
      |> assign(assigns)
      |> assign_messages(new_channel_name)

    {:ok, socket}
  end

Can’t I get the old assigns in update/2 callback of LiveComponent?

page: Home · Json Media
code: json_corp/channel.ex at chat · nallwhy/json_corp · GitHub

Where do you assign channel_name?

You have an id of the dom element based on the channel name. If the channel name changes then the id changes, which means you’re instantiating a new live component instead of reusing the existing one.

2 Likes

Thank you so much!

1 Like

No problem! Thanks so much for having the full code up, it makes answering these sorts of questions super easy!

1 Like

Bumping into this quite a lot. id vs DOM.id, when it should be unique and when not, how to guarantee that, is one of those topics that are a little vague.