I am new to Elixir and Phoenix, so I apologize if the question is stupid.
I am developing an ecommerce site, and I have a cart drawer located in a layout, using LiveComponent.
After adding an item to cart from another component, that as I understand it, lives in another process, I want to send an update to this LiveComponent so that it updates without a page refresh or navigation.
I found send_update
which seems to do what I want Phoenix.LiveView — Phoenix LiveView v1.0.0-rc.1
To use this, I need to find PID of this other Liveview. Things I tried:
Process.info(self())
Does not return assigned name of the processProcess.register(self(), :cart_liveview)
Fails due to a name already existing- Using the
id
that I pass tolive_render
from the layout, to render everything. Does not find it.
I am using Process.whereis
to get PID from name.
Relevant code:
handle_event
snippet on product page
# Save
properties_enc = Jason.encode!(values)
Carts.add_to_cart(cart_id, product_id, properties_enc)
# PID<0.4190.0>
pid = Process.whereis(:cart_liveview)
send_update(CartModal, id: "cart_modal", hello: "from_save")
{:noreply,
socket
|> push_event("js-exec", %{
to: "#confirm-modal",
attr: "data-show-drawer"
})}
Liveview load on layout
<div class="flex items-center gap-4 font-semibold leading-6 text-zinc-900">
<%= live_render(@socket, PhoenixDemoWeb.Layouts.Components.CartLiveView, id: :cart_liveview) %>
</div>
Live Component load
defmodule PhoenixDemoWeb.Layouts.Components.CartLiveView do
use PhoenixDemoWeb, :live_view
alias PhoenixDemoWeb.PutCartCookie
alias PhoenixDemo.Carts
@impl true
def mount(_params, session, socket) do
# Load cart
cart_id = session[PutCartCookie.cart_id_cookie_name()]
cart = Carts.get_cart_with_products(cart_id)
socket = assign(socket, cart: cart)
{:ok, socket}
end
@impl true
def render(assigns) do
~H"""
<.live_component
module={PhoenixDemoWeb.Layouts.Components.CartModal}
id="cart_modal"
cart={@cart}
/>
"""
end
end
Any ideas? Does what I’m doing even make sense?