View Source Rephex (rephex v0.1.1)
defmodule RephexPgWeb.State do
@initial_state %{
count: 0,
}
use Rephex.State, initial_state: @initial_state
def add_count(socket, %{amount: amount} = _payload) when is_integer(amount) do
# You can use `update_state`, `update_state_in` and `put_state_in` to update state
update_state_in(socket, [:count], &(&1 + amount))
end
end
defmodule RephexPgWeb.AccountLive.Index do
alias RephexPgWeb.State
use RephexPgWeb, :live_view
use Rephex.LiveView
alias Phoenix.LiveView.{AsyncResult, Socket}
alias RephexPgWeb.AccountLive.ComponentA
@impl true
def mount(_params, _session, %Socket{} = socket) do
{:ok, socket |> State.init()}
end
@impl true
def handle_event("add_count", %{"amount" => amount}, %Socket{} = socket) do
{am, _} = Integer.parse(amount)
{:noreply, socket |> State.add_count(%{amount: am})}
end
@impl true
def render(assigns) do
# At default, Rephex state is assigned at `:rpx`.
# You can change root key by config.
~H"""
<div>Count: <%= @rpx.count %></div>
<button class="border-2" phx-click="add_count" phx-value-amount={1}>
[Add Count 1]
</button>
<.live_component module={ComponentA} id="cmp_a" rpx={@rpx} />
"""
end
end
defmodule RephexPgWeb.AccountLive.ComponentA do
use RephexPgWeb, :live_component
use Rephex.LiveComponent
alias Phoenix.LiveView.Socket
@initial_local_state %{}
@impl true
def mount(%Socket{} = socket) do
{:ok, socket |> assign(@initial_local_state)}
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> propagate_rephex(assigns)}
end
@impl true
def handle_event("add_count", %{"amount" => amount}, %Socket{} = socket) do
{am, _} = Integer.parse(amount)
{:noreply,
socket
|> call_in_root(fn socket ->
State.add_count(socket, %{amount: am})
end)}
end
@impl true
def render(assigns) do
~H"""
<button class="border-2" phx-click="add_count" phx-value-amount={2} phx-target={@myself}>
[Add Count 2]
</button>
"""
end
end
Summary
Functions
@spec root() :: atom()
Get root key of Rephex state. Default key is :rpx
.
Rephex state will be contained at socket.assigns[Rephex.root()]
.
You can change key by config.
Example:
config :rephex, root: :my_rpx