Control the route transition
Observe one transition from the active route through the completed destination.
The example opens Profile, reports the attempt to leave, moves to Home and reports the completed change. Router failures use the same error flow.
Table of contents
Main APIs
- redirect
- Starts navigation to the supplied URL and optionally avoids pushing browser history.
- beforeRoute
- Observes attempts to leave the current route.
- afterRoute
- Observes completed route changes.
- RouterError
- Represents a router failure exposed for application-level handling.
tsximport { mount, onCreate } from "valyrian.js";
import {
afterRoute,
beforeRoute,
mountRouter,
redirect,
Router,
} from "valyrian.js/router";
const status = { message: "Open the profile route." };
const Home = () => (
<main>
<p>{status.message}</p>
<button onclick={() => redirect("/profile")}>Open profile</button>
</main>
);
const Profile = () => {
onCreate(() => {
beforeRoute(() => {
status.message = "Leaving profile";
return true;
});
afterRoute(() => {
status.message = "Route changed";
});
});
return (
<main>
<p>Profile</p>
<button onclick={() => redirect("/")}>Leave profile</button>
</main>
);
};
const router = new Router();
router.add("/", Home);
router.add("/profile", Profile);
router.catch((_request: { path: string }, error?: unknown) => (
<main>
Navigation failed:{" "}
{error instanceof Error ? error.message : "Unknown error"}
</main>
));
mountRouter("body", router);Starting point
Start with a Router mounted on body and at least two routes so one transition can leave an active component.
Action
Open Profile, then choose Leave profile. The profile component registers both hooks during onCreate, and the buttons navigate through redirect.
Result
The example opens a profile route, reports the attempt to leave it and reports the completed transition on the destination route.