Defmodule test.thermostatlive do
# in phoenix v1.6+ apps, the line is typically: use myappweb, :live_view
Use phoenix.liveview
# use phoenix.livecomponent

Def render(assigns) do
~h"""
<%= for {id, card} <- @cards do %>
<.live_component module={cardcomponent} id={id} card={card} />
<% end %>
<hr />
<div>
<button name="foo" phx-click="click">update all</button>
</div>
"""
End

Def mount(_params, _session, socket) do
Io.inspect("mount")
Cards = %{"first" => %{title: "foo"}, "second" => %{title: "bar"}}
{:ok, assign(socket, :cards, cards)}
End

Def handle_event("click", _, socket) do
Io.puts("click root")
# update all the cards
Cards =
Socket.assigns.cards
|> enum.map(fn {id, card} -> {id, %{card | title: card.title <> "."}} end)
|> enum.into(%{})

{:noreply, assign(socket, :cards, cards)}
End

Def handle_info({:updated_card, %{title: title}, id}, socket) do
Io.puts("updated_card")

Old_cards = socket.assigns.cards
New_cards =map.put(old_cards, id, %{title: title})
Socket = assign(socket, :cards, new_cards)
{:noreply, socket}
End
End

Defmodule cardcomponent do
Use phoenix.livecomponent

Def render(assigns) do
~h"""
<div>
<button name="foo" phx-click="click" phx-target={@myself}><%= @card.title %></button>
</div>
"""
End

Def handle_event("click", _, socket) do
Io.puts("click component")
# socket.assign()
Old_card = socket.assigns.card
New_card = %{old_card | title: old_card.title <> "."}

Io.inspect socket.assigns
# notify the root lv that state has changed
Send self(), {:updated_card, new_card, socket.assigns.id}

{:noreply, assign(socket, :card, new_card)}
End
End