Skip to content

Function: buildRouteUrl()

API / @xmachines/play-xstate / with-routing / buildRouteUrl

function buildRouteUrl(routeTemplate, context?, options?): string;

Defined in: packages/play-xstate/src/routing/build-url.ts:46

Builds a complete URL from a route template and the context of the actor.

The function replaces each :param placeholder and each :param? placeholder with a value of context.params. It then appends the query params and the hash fragment.

Every parameter value must be in context.params. The function reads no flat context field, and this is deliberate: a placeholder with a spelling error therefore gives a compile-time error, and it does not resolve to undefined in silence.

Parameters

ParameterTypeDescription
routeTemplatestringThe template of the route path, for example "/profile/:userId" or "/settings/:section?".
contextRouteContextThe context object of the actor. Each route parameter must be in context.params, because the function reads no flat context field. An absent query field builds a URL without a query, exactly like query: {}.
options?ParseOptionsThe caches to read, as ParseOptions. The default is the cache that @xmachines/play-pattern shares with every caller of the process. A parse is deterministic, so this changes how often the parser runs and it changes no answer.

Returns

string

The complete URL string.

Throws

When a necessary :param placeholder has no value in the context. The function omits an optional parameter (:param?) in silence when its value is absent. Import the class from @xmachines/play-xstate/errors.

Throws

When a :param placeholder carries a dot segment, which a URL resolves away. The template matches the built URL back never, so the actor and the address bar would stay out of step.

Example

buildRouteUrl("/user/:id", { params: { id: "123" }, query: { tab: "profile" }, hash: "top" });
// → "/user/123?tab=profile#top"
buildRouteUrl("/settings/:section?", { params: {}, query: {} });
// → "/settings" (the optional param is absent, and there is no query string)