Skip to content

Function: deriveRoute()

API / @xmachines/play-xstate / deriveRoute

function deriveRoute(stateMeta): string | null;

Defined in: packages/play-xstate/src/routing/derive-route.ts:92

Derives the route from the metadata of an XState state

The function reads the URL template of the route from the meta.route field in the metadata of the active state. It supports a string route ("/about") and also an object route with a path property ({ path: "/about" }). It returns null for a state without route metadata, because not every state needs a route.

Architectural context: the function implements Actor Authority (INV-01), because it reads the routing information from the state machine definition, and not from an external configuration. The current state of the Actor decides the route, and no decision of the infrastructure decides it.

Parameters

ParameterTypeDescription
stateMetaRecord<string, unknown>The state metadata from snapshot.getMeta()

Returns

string | null

The template of the route path, which can hold a :param, or null when the function finds no route

Examples

The basic read of a route

import { deriveRoute } from "@xmachines/play-xstate";
import { setup } from "xstate";
const machine = setup({}).createMachine({
states: {
about: {
meta: { route: "/about", view: { component: "AboutPage" } },
},
},
});
const actor = createActor(machine);
actor.start();
const snapshot = actor.getSnapshot();
const meta = snapshot.getMeta();
const route = deriveRoute(meta);
console.log(route); // "/about"

A route with a parameter

const machine = setup({}).createMachine({
states: {
profile: {
meta: {
route: "/profile/:userId",
view: { component: "ProfilePage", userId: (ctx) => ctx.userId },
},
},
},
});
const route = deriveRoute(snapshot.getMeta());
console.log(route); // "/profile/:userId" — the template, before the substitution

The object form of a route

const machine = setup({}).createMachine({
states: {
dashboard: {
meta: {
route: { path: "/dashboard" },
view: { component: "Dashboard" },
},
},
},
});
const route = deriveRoute(snapshot.getMeta());
console.log(route); // "/dashboard"

See

Remarks

This function reads the route definition from meta.route. A state with a route: {} config has a route. buildRouteUrl substitutes each parameter, and this function does not: deriveRoute returns a template.

A state without a route: a state without a meta.route field gives null. This is deliberate, because not every state needs a route. An intermediate loading state and a substate, for example, often have no URL of their own.