Skip to content

Instantly share code, notes, and snippets.

@msimonborg
Last active Jun 8, 2022
Embed
What would you like to do?
defmodule AppWeb.Router do
# ...
scope "/", AppWeb do
pipe_through :browser
live "/test", TestLive
end
end
defmodule AppWeb.TestComponent do
use AppWeb, :live_component
def render(assigns) do
~H"""
<div>
<.form let={_f} for={:form} action="#" phx-submit="submit">
<%= submit("submit") %>
</.form>
<%= if @redirected do %>
<p>redirected</p>
<% end %>
</div>
"""
end
end
defmodule AppWeb.TestLive do
use AppWeb, :live_view
@impl true
def render(assigns) do
~H"""
<.live_component module={AppWeb.TestComponent} id={1} {assigns}/>
"""
end
@impl true
def mount(_params, _session, socket) do
socket =
socket
|> assign_defaults()
|> assign_new(:redirected, fn -> false end)
{:ok, socket, layout: false}
end
defp assign_defaults(socket) do
attach_hook(socket, :set_current_url, :handle_params, fn
_params, url, socket ->
uri = URI.parse(url)
if uri.query do
{:cont, assign(socket, current_url: uri.path <> "?" <> uri.query)}
else
{:cont, assign(socket, current_url: uri.path)}
end
end)
end
@impl true
def handle_event("submit", _, socket) do
if socket.assigns.current_url do
{:noreply, assign(socket, :redirected, true)}
else
{:noreply, socket}
end
end
end
defmodule AppWeb.TestLiveTest do
use AppWeb.ConnCase
import Phoenix.LiveViewTest
test "renders redirected", %{conn: conn} do
{:ok, view, html} = live(conn, Routes.live_path(conn, AppWeb.TestLive))
assert html =~ "submit"
refute html =~ "redirected"
view
|> element("form")
|> render_submit()
assert render(view) =~ "redirected"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment