Skip to content

Instantly share code, notes, and snippets.

@mazz
Created January 30, 2021 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mazz/b76c4a3b8d15222dbfdaebf5b3f080cb to your computer and use it in GitHub Desktop.
Save mazz/b76c4a3b8d15222dbfdaebf5b3f080cb to your computer and use it in GitHub Desktop.
cart_live
defmodule RedpillsWeb.CartLive do
use Phoenix.LiveView
alias RedpillsWeb.Router.Helpers, as: Routes
require Logger
@impl true
def mount(_params, session, socket) do
shopping_cart = Map.get(session, "shopping_cart", [])
IO.inspect(shopping_cart, label: "RedpillsWeb.CartLive shopping_cart")
socket =
socket
|> PhoenixLiveSession.maybe_subscribe(session)
|> assign(:count, Integer.to_string(length(shopping_cart)))
socket = assign(socket, conn: socket)
{:ok, socket}
end
@impl true
def handle_event("checkout-items", session, socket) do
Logger.info("checkout-items")
{:noreply, socket}
end
@impl true
def handle_info({:live_session_updated, %{"shopping_cart" => shopping_cart} = session}, socket) do
IO.inspect(session, label: "cart_live live_session_updated session")
{:noreply, assign(socket, count: Integer.to_string(length(shopping_cart)))}
end
def handle_info({:live_session_updated, _session}, socket) do
{:noreply, socket}
end
@impl true
def render(assigns) do
~L"""
<div class="flex items-center">
<svg class="w-8 h-8" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path d="M3 1a1 1 0 000 2h1.22l.305 1.222a.997.997 0 00.01.042l1.358 5.43-.893.892C3.74 11.846 4.632 14 6.414 14H15a1 1 0 000-2H6.414l1-1H14a1 1 0 00.894-.553l3-6A1 1 0 0017 3H6.28l-.31-1.243A1 1 0 005 1H3zM16 16.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0zM6.5 18a1.5 1.5 0 100-3 1.5 1.5 0 000 3z" />
</svg>
<%= if String.to_integer(@count) == 0 do %>
<span>No items</span>
<% else %>
<%= if String.to_integer(@count) == 1 do %>
<a href="<%= Routes.subscription_new_path(@conn, :new) %>" class="btn btn-dark" role="button">
Checkout <%= @count %> item
</a>
<% else %>
<%= if String.to_integer(@count) > 1 do %>
<a href="<%= Routes.subscription_new_path(@conn, :new) %>" class="btn btn-dark" role="button">
Checkout <%= @count %> items
</a>
<link href="<%= Routes.subscription_new_path(@conn, :new) %>"/>
<% end %>
<% end %>
<% end %>
</div>
"""
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment