Live view - lack of DOM update for connected clients

I have this quite simple code:

$ cat controllers/players_controller.ex 
defmodule AppWeb.PlayersController do
  use AppWeb, :controller

  def list(conn, _params) do
    conn
    |> live_render(AppWeb.PlayersLive)
  end
end

$ cat live/players_live.ex 
defmodule AppWeb.PlayersLive do
  use AppWeb, :live_view
  alias App.Users

  def mount(_params, _session, socket) do
    {:ok,
      socket
      |> assign(:players, Users.get_players())
    }
  end

  def handle_event("role_change", params, socket) do
    %{"change_role" => data} = params

    [user_id] = Map.keys(data)
    user_id = String.to_integer(user_id)

    [role] = Map.values(data)

    Users.set_role(user_id, role)

    {:noreply,
      socket
      |> assign(:players, Users.get_players())
    }
  end
end

$ cat live/players_live.html.leex 
...
  <%= for {id, name, email, role, num} <- @players do %>
    <tr>
      <td>
        <%= num %>.
      </td>
      <td>
        <a href="mailto:<%= email %>"><%= name %></a>
      </td>
      <td>
        <%= f = form_for :change_role, "#", [phx_change: :role_change] %>
          <%= select f, "#{id}", ["user", "super", "admin"], selected: "#{role}", class: "change_role" %>
        </form>
      </td>
    </tr>
  <% end %>
...
$ cat ../app/users.ex
...
  def get_players() do
    Repo.all(from u in User,
      select: {u.id, u.name, u.email, u.role, row_number() |> over(order_by: u.id)}
    )
  end
...

And handling the phx_change event is working OK (the role for given user is changed in the database).
But I would expect that all clients that are on that page will be “DOM patched” when the role of user has been changed. But that doesn’t happening. Why?

Every connected client has a AppWeb.PlayersLive process connection. So handle_event is executed for one client.
When you update your assigns, it happens for one client only. If you want to update all connected clients you have to let them know about the change, for example by sending messages with Phoenix.PubSub.broadcast

1 Like

Hahah ok. I was approaching to live view too optimistic. Butt seems that pub/sub isn’t that hard to add anyway! Thank you.