Skip to content

Function: buildRouteUrl()

API / @xmachines/play-xstate / buildRouteUrl

function buildRouteUrl(routeTemplate, context?): string;

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

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: {}.

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.

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)