Skip to content

Function: getRouteMappings()

API / @xmachines/play-router / xstate / getRouteMappings

function getRouteMappings(tree, options?): RouteMapping[];

Defined in: packages/play-router/src/xstate/query.ts:258

Returns the { stateId, path } entries that a host router needs, so that it can register the routes of a machine under a base path, and remove them again later.

This function makes the routes dynamic. getStateIdByPath and getPathByStateId answer the question “what is this URL?” at the moment of a navigation, but a host that declares real route objects — a route tree of TanStack, a RouteObject[], an addRoute call of vue-router — needs the LIST in advance, and it needs that list with the prefix of the mount. A registration of these paths, and a removal of them when the machine unloads, keeps the route table of the host in step with the mount.

basePathParams decides the form of each path, and both forms are useful:

  • Given → a concrete path (/abc123/play/profile/:userId), for a route that the host adds at run time, after a loader resolved the mount.
  • Absent → the pattern stays (/:machineId/play/profile/:userId), for a static route declaration of the host.

The function ALWAYS keeps each :param segment that the machine declares itself: those are the params that the route of the host must match.

Parameters

ParameterTypeDescription
treeRouteTreeThe route tree of extractMachineRoutes()
options?BasePathOptionsThe optional { basePath, basePathParams }, the same option as the bridge takes. Each stateId comes from the route tree, so it carries NO # prefix. A host that keys its route table on the target of a play.route event adds the # itself, because the event always carries the prefixed form.

Returns

RouteMapping[]

One entry for each state with a route, in the order of the route tree.

Throws

For a base path that resolves to one concrete path never.

Throws

When basePathParams is present and it omits a :param.

Example

const tree = extractMachineRoutes(machine);
// Concrete, for a route that the host adds after a loader resolved the mount
getRouteMappings(tree, { basePath: "/:machineId/play", basePathParams: { machineId: "abc123" } });
// [
// { stateId: "app.home", path: "/abc123/play" },
// { stateId: "app.profile", path: "/abc123/play/profile/:userId" },
// ]
// The pattern, for a static route declaration of the host
getRouteMappings(tree, { basePath: "/:machineId/play" });
// [{ stateId: "app.home", path: "/:machineId/play" }, ...]