@consumeContext
Use @consumeContext(...) to inject the nearest matching context provider onto a field.
It works on both RadiantElement and RadiantController hosts.
Example
import { RadiantElement, customElement } from '@ecopages/radiant';
import { consumeContext, type ContextProvider } from '@ecopages/radiant/context';
import { themeContext } from './theme-provider';
@customElement('theme-label')
export class ThemeLabel extends RadiantElement {
@consumeContext(themeContext)
provider!: ContextProvider<typeof themeContext>;
override connectedCallback() {
super.connectedCallback();
this.textContent = `Theme: ${this.provider.getContext().mode}`;
}
}The injected field gives you access to the provider API, including getContext() and setContext(...).
On controllers, this is often the simplest way to read and write shared state imperatively from event handlers or render().
When To Use It
- Use
@consumeContext(...)when the host needs the provider object to callgetContext()orsetContext(...). - Use @contextSelector when the host should bind a field to the current context value and rerender automatically.
- Use @onContextUpdate when a context change should trigger imperative side effects.
RadiantController Example
import { RadiantController } from '@ecopages/radiant';
import { consumeContext, type ContextProvider } from '@ecopages/radiant/context';
import { themeContext } from './theme-provider';
export class ThemePanelController extends RadiantController {
@consumeContext(themeContext)
provider!: ContextProvider<typeof themeContext>;
override render() {
return <p>Theme: {this.provider.getContext().mode}</p>;
}
}Client And SSR Behavior
- During SSR the field can resolve from the active SSR context stack.
- On the client it falls back to the DOM event-based context channel.
Multiple Contexts
One host can consume multiple contexts by applying the decorator to multiple fields.
@consumeContext(themeContext) theme!: ContextProvider<typeof themeContext>;
@consumeContext(authContext) auth!: ContextProvider<typeof authContext>;Manual Alternative
If you need lower-level control, you can dispatch a context request event directly.
import { RadiantElement, customElement } from '@ecopages/radiant';
import { ContextRequestEvent } from '@ecopages/radiant/context';
import { themeContext } from './theme-provider';
@customElement('theme-label')
export class ThemeLabel extends RadiantElement {
override connectedCallback() {
super.connectedCallback();
this.dispatchEvent(
new ContextRequestEvent(themeContext, (provider) => {
this.textContent = `Theme: ${provider.getContext().mode}`;
}),
);
}
}ContextRequestEvent follows the community context protocol. Pass true as the third argument to subscribe to future updates.
ContextSubscriptionRequestEvent and ContextEventsTypes are also available from @ecopages/radiant/context.