Skip to content

injectContextSync

ts
injectContextSync<T>(el: Element, key: ContextKey<T>): T | undefined

The nearest provided value, synchronously, or undefined.

Usage

ts
const 
value
=
injectContextSync
(
el
,
Key
);
if (
value
===
undefined
) {
// no provider — fall back, or do nothing }

When to reach for it

When the answer is optional and the caller has a fallback. undefined means "no provider right now", which is a different statement from $inject()'s "not yet".

The canonical pair is a look-up-or-create:

ts
const 
channels
=
injectContextSync
(
el
,
DataChannels
) ??
provideRootContext
(
DataChannels
, () => new
Map
());

From a component

$injectSync(key) is the same call with the element filled in.

It answers for right now

A provider that mounts later is not seen, because there is no request left pending. If mount order is not something you control, use injectContext() or subscribeContext().

MIT Licensed