Live View Store Data in URL Params: Difference between revisions
From ElixirBlocks
(Created page with "<source> defmodule AppWeb.PageLive do use AppWeb, :live_view def mount(_params, _session, socket) do {:ok, socket} end def handle_params(params, _uri, socket) do count = String.to_integer(params["count"] || "0") {:noreply, assign(socket, count: count)} end def handle_event("increment", _, socket) do new_count = socket.assigns.count + 1 # Use ~p instead of Routes {:noreply, push_patch(socket, to: ~p"/?count=#{new_count}")} end d...") |
(No difference)
|
Latest revision as of 15:24, 16 April 2025
defmodule AppWeb.PageLive do
use AppWeb, :live_view
def mount(_params, _session, socket) do
{:ok, socket}
end
def handle_params(params, _uri, socket) do
count = String.to_integer(params["count"] || "0")
{:noreply, assign(socket, count: count)}
end
def handle_event("increment", _, socket) do
new_count = socket.assigns.count + 1
# Use ~p instead of Routes
{:noreply, push_patch(socket, to: ~p"/?count=#{new_count}")}
end
def handle_event("decrement", _, socket) do
new_count = max(0, socket.assigns.count - 1)
# Use ~p instead of Routes
{:noreply, push_patch(socket, to: ~p"/?count=#{new_count}")}
end
def render(assigns) do
~H"""
<div>
<h1>Count: <%= @count %></h1>
<button phx-click="decrement">-</button>
<button phx-click="increment">+</button>
</div>
"""
end
end