Skip to content

lit-ui-router / withRouterSync

Variable: withRouterSync

ts
const withRouterSync: <T>(router, run) => T;

Defined in: packages/lit-ui-router/src/context.ts:349

Runs run with router published to `getScopedRouter`, restoring whatever was there before — undefined included — when it returns or throws.

This is the tree-less provider. A context-request needs a tree to bubble through, which is what `provideRouter` serves; withRouterSync publishes a router for one synchronous call instead, so code with no element — a server render, a test — asks getScopedRouter().

The Sync suffix names the constraint the thenable guard enforces, in the convention of collectResultSync. @lit-labs/ssr's render() returns a sync generator, so a whole render happens inside run as long as the caller consumes it there: collectResultSync(render(template)). Nothing is detected and nothing is upgraded — if run returns a thenable the slot is restored and a TypeError is thrown, because anything that promise does later reads a slot that is already gone.

Calls nest: an inner call sees its own router, and the outer one is restored on the way out.

The router is any @uirouter/core UIRouter: the directives that read the slot want stateService, stateRegistry, transitionService and globals, none of which UIRouterLit adds, so a caller that types its router as UIRouter — the type UIViewInjectedProps.router declares — passes it here unchanged.

Type Parameters

Type ParameterDescription
Twhatever run returns

Parameters

ParameterTypeDescription
routerUIRouterthe router to publish for the duration of run
run() => Tthe call the router is scoped to, consumed synchronously

Returns

T

whatever run returned

Throws

a TypeError if run returns a thenable

Example

ts
import { render } from '@lit-labs/ssr';
import { collectResultSync } from '@lit-labs/ssr/lib/render-result.js';
import { withRouterSync } from 'lit-ui-router/context';

const markup = withRouterSync(router, () =>
  collectResultSync(render(html`<my-page></my-page>`)),
);