Skip to content

Instantly share code, notes, and snippets.

@andreaseriksson
Created January 27, 2021 07:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andreaseriksson/e2f9779e4c0c3faa9e70200527b95055 to your computer and use it in GitHub Desktop.
Save andreaseriksson/e2f9779e4c0c3faa9e70200527b95055 to your computer and use it in GitHub Desktop.
Use phoenix_live_session to communicate bewteen live views
<%= live_render @conn, EcommerceWeb.CartLive %>
defmodule EcommerceWeb.CartLive do
use Phoenix.LiveView
@impl true
def mount(_params, session, socket) do
socket =
socket
|> PhoenixLiveSession.maybe_subscribe(session)
|> assign(:count, 0)
{:ok, socket}
end
@impl true
def handle_info({:live_session_updated, %{"count" => count} = _session}, socket) do
{:noreply, assign(socket, count: count)}
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-5 h-5" 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>
<span><%= @count %></span>
</div>
"""
end
end
defmodule EcommerceWeb.PageLive do
use EcommerceWeb, :live_view
@impl true
def mount(_params, session, socket) do
socket =
socket
|> PhoenixLiveSession.maybe_subscribe(session)
|> assign(:count, 0)
{:ok, socket}
end
@impl true
def handle_info({:live_session_updated, %{"count" => count} = _session}, socket) do
{:noreply, assign(socket, count: count)}
end
def handle_info({:live_session_updated, _session}, socket) do
{:noreply, socket}
end
@impl true
def handle_event("add-product", _, socket) do
count = socket.assigns.count + 1
PhoenixLiveSession.put_session(socket, "count", count)
{:noreply, socket}
end
end
<button type="submit" class="btn btn-dark" phx-click="add-product">Add</button> <%= @count %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment