LocalLiveView.Router (LocalLiveView v0.1.0)

Copy Markdown View Source

Phoenix router macro for mounting a LocalLiveView at a route.

Import this module in your Phoenix router:

defmodule MyAppWeb.Router do
  use MyAppWeb, :router
  import LocalLiveView.Router

  scope "/" do
    pipe_through :browser
    live_local "/plain", HelloLocal
  end
end

Summary

Functions

Mounts a local live view at path, on a plain page with no host LiveView.

Functions

live_local(path, view_module)

(macro)

Mounts a local live view at path, on a plain page with no host LiveView.

Use it when the view needs no assigns from the server — the route renders nothing but the mount point, as if the page contained a single LocalLiveView.Component.local_live_view/1 call:

live_local "/counter", CounterLocal

A view that receives assigns from the server, pushes events to it with LocalLiveView.push_server_event/3 or handles LocalLiveView.handle_push_error/4 needs a host LiveView to talk to. Then route to your own LiveView with live/4 and render the component inside its template, which is where the assigns come from and where the pushed events land:

# router.ex
live "/cart", CartLive

# cart_live.ex
defmodule MyAppWeb.CartLive do
  use MyAppWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok, assign(socket, :items, Store.list_items())}
  end

  def render(assigns) do
    ~H"""
    <h1>Cart</h1>
    <.local_live_view view="CartLocal" items={@items} />
    """
  end

  # Receives what the local view sends with push_server_event/3
  def handle_event("archive", %{"id" => id}, socket) do
    {:noreply, assign(socket, :items, Store.archive(id))}
  end
end

view_module is taken by its last alias segment, so HelloLocal and MyApp.HelloLocal both resolve to the "HelloLocal" view in the local/ project. A string or atom works too.