@contextSelector
The @contextSelector decorator is used to consume a specific property of a context. This decorator takes an object with the following properties:
context: The context object that you want to consume.select: The property of the context that you want to consume.subscribe: A boolean that indicates if the consumer should subscribe to changes in the context.
If subscribe is set to true, the consumer will be updated whenever the context value changes.
This decorator is a method decorator, so it should be used on a method of a class that will be triggered when the context value changes.
Here is an example of how to use the @contextSelector decorator:
import { MyContext } from './my-element-provider'
@customElement("my-consumer")
export class MyElement extends RadiantElement {
@contextSelector({ context: todoContext, select: ({ value }) => ({ value }) })
handleValue({ value }: Pick<MyContext, 'value'>) {
console.log(value);
}
}
This can be very handy when you need to manipulate the context value before using it.
import { MyContext } from './my-element-provider'
@customElement("my-consumer")
export class MyElement extends RadiantElement {
@contextSelector({
context: todoContext,
select: ({ value }) => ({ value: value.map((item) => item + 1) }),
})
handleValue({ value }: Pick<MyContext, 'value'>) {
console.log(value);
}
}
If for any reason you don't want to use the @contextSelector decorator, you can subscribe to the context changes manually.
import { MyContext } from './my-element-provider'
@customElement("my-consumer")
export class MyElement extends RadiantElement {
context!: ContextProvider<typeof myContext>;
connectedCallback() {
super.connectedCallback();
this.onChangeValue = this.onChangeValue.bind(this);
this.dispatchEvent(
new ContextRequestEvent(contextToProvide, (context) => {
this.context = context;
this.context.subscribe({ select: 'value', callback: this.onChangeValue });
}),
);
}
onChangeValue({ value }: Pick<MyContext, 'value'>) {
console.log(value);
}
}