Here’s an approach that works:
some_random_live_view.html.heex
<div id="auto-redirect" phx-hook="AutoRedirect">
Auto Redirecting in 3, 2, 1
</div>
auto_redirect.js
const AutoRedirect = {
mounted() {
setTimeout(() => {
this.pushEvent(
"navigate",
"/blog/taskfile-a-sensible-makefile-and-shell-script-alternative"
);
}, 3000);
},
};
export default AutoRedirect;
some_random_live_view.ex
defp handle_event("navigate", route, socket) do
{:noreply,
socket
|> push_navigate(to: route)}
end
You can handle event on each live view, or use on_mount
, together with live_session
.
nav.ex
defmodule DerpyToolsWeb.Nav do
import Phoenix.LiveView
use Phoenix.Component
def on_mount(:default, _params, _session, socket) do
{:cont,
socket
|> attach_hook(:auto_redirect, :handle_event, &handle_event/3)
|> attach_hook(:inspect_source, :handle_event, &handle_event/3)
end
defp handle_event("navigate", route, socket) do
{:halt,
socket
|> push_navigate(to: route)}
end
end
router.ex
scope "/", DerpyToolsWeb do
pipe_through :browser
live_session :no_log_in_required,
on_mount: [
DerpyToolsWeb.Nav,
{DerpyToolsWeb.Permit, :anyone}
] do
live "/", HomePageLive
live "/blog/:post_slug", BlogLive
end
end