Search⌘ K
AI Features

Update Shopping Carts in Real-time

Explore how to implement real-time shopping cart updates using Phoenix Presence. Learn to track cart changes across sessions and view live updates within the admin dashboard, enhancing your application's responsiveness and user interaction.

Updating the cart

We’ll hook into two different functions to update the tracked cart:

  1. When the Channel broadcasts its cart.
  2. When it receives a broadcast that the cart contents have changed.

Add the highlighted send/2 function calls in the existing ShoppingCartChannel functions.

Elixir
# sneakers_23_admin/lib/sneakers_23_web/channels/shopping_cart_channel.ex
def handle_info(:update_tracked_cart, socket = %{
assigns: %{cart: cart, cart_id: id}
}) do
{:ok, _} = Sneakers23Web.CartTracker.update_cart(
socket, %{cart: cart, id: id}
)
{:noreply, socket}
end
def handle_out("cart_updated", params, socket) do
modify_subscriptions(params)
cart = get_cart(params)
socket = assign(socket, :cart, cart)
push(socket, "cart", cart_to_map(cart))
send(self(), :update_tracked_cart)
{:noreply, socket}
end
defp broadcast_cart(cart, socket, opts) do
send(self(), :update_tracked_cart)
{:ok, serialized} = Checkout.export_cart(cart)
broadcast_from(socket, "cart_updated", %{
"serialized" => serialized,
"added" => Keyword.get(opts, :added, []),
"removed" => Keyword.get(opts, :removed, [])
})
end

Presence works by sending an initial state to a client and keeping that state up to date by pushing changes. We need to send the initial state ourselves in the Admin.DashboardChannel. Add the following ...