piacere です、ご覧いただいてありがとございます
LiveViewのコンポーネントである「LiveComponent」は、他SPA FW同様、画面パーツおよびパラメータのコンポーネント化に便利です
しかし、LiveComponent内で閉じた非同期処理は、1つ前のバージョンであるLiveView 0.19までは実現がやりにくかったです
最新バージョンであるLiveView 0.20以降では、これがカンタンに実現できるようになったので、下記にコードを示します
ポイントは、LiveView 0.20で追加された assign_async
と handle_async
の連携です
lib/basic_web/live/sample_live/index.ex
defmodule BasicWeb.SampleLive.Index do
use BasicWeb, :live_view
end
defmodule HeroComponent do
use Phoenix.LiveComponent
def mount(socket), do: {:ok, assign(socket, :list, [])}
def handle_event("say_hello", _, socket), do: {:noreply, assign_async(socket, :list, &run/0)}
def handle_async(:result, {:ok, result}, socket), do: {:ok, socket}
def run() do
Process.sleep(1000)
{:ok, %{list: [:rand.uniform(10)]}}
end
def render(assigns) do
~H"""
<a href="#" phx-click="say_hello" phx-target={@myself}>
<p>Say hello!</p>
<p><%= inspect @list %></p>
</a>
"""
end
end
下記で試してみてください
lib/basic_web/live/sample_live/index.html.heex
<.live_component module={HeroComponent} id="hero" />
lib/basic_web/router.ex
defmodule BasicWeb.Router do
use BasicWeb, :router
…
scope "/", BasicWeb do
pipe_through :browser
live "/sample", SampleLive.Index, :index
get "/", PageController, :home
end
…