initial shared counter state, with flaw that each new windows resets counter to 0...

This commit is contained in:
Peter Hart 2022-08-28 13:07:20 -04:00
parent 50e48e7d0e
commit 87e5e79c04

View File

@ -1,16 +1,27 @@
defmodule LiveViewCounterWeb.Counter do
use Phoenix.LiveView
@topic "live"
def mount(_params, _session, socket) do
LiveViewCounterWeb.Endpoint.subscribe(@topic)
{:ok, assign(socket, :val, 0)}
end
def handle_event("inc", _, socket) do
{:noreply, update(socket, :val, &(&1 + 1))}
new_state = update(socket, :val, &(&1 + 1))
LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "inc", new_state.assigns)
{:noreply, new_state}
end
def handle_event("dec", _, socket) do
{:noreply, update(socket, :val, &(&1 - 1))}
new_state = update(socket, :val, &(&1 - 1))
LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "dec", new_state.assigns)
{:noreply, new_state}
end
def handle_info(msg, socket) do
{:noreply, assign(socket, val: msg.payload.val)}
end
def render(assigns) do