v 0.2.0

@provideContext


To provide a context to a component, you can use the @provideContext decorator. This decorator takes an object with the following properties:

@customElement("my-context")
export class MyElement extends RadiantElement {
	@provideContext({ context: myContext, initialValue: { value: "Hello World" } })
	provider!: ContextProvider<typeof myContext>;
}

If you want to hydrate the context with the data from the server, you can use the hydrate property and pass an AttributeType that will be used to hydrate the context with the data from the server.

The attribute type can be a String, Number, Boolean, Object, or Array.

@customElement("my-context")
export class MyElement extends RadiantElement {
	@provideContext({ context: myContext, initialValue: { logger: new Logger() }, hydrate: Object})
	provider!: ContextProvider<typeof myContext>;
}

Once defined, the context provider will search for a script tag with the attribute data-hydration and will use the content of the script tag to hydrate the context.

This way we follow the best practices to provide complex data to a component.

<my-context-provider>
	<script type="application/json" data-hydration>
		{"value": "Hello World"}
	</script>
</my-context-provider>

If you are using jsx you can use the stringifyTyped function to stringify the data. It will stringify the data in a typed way, which is useful when you need to pass attributes to a component that expects a specific type.

import { stringifyTyped } from '@ecopages/radiant/tools/stringify-typed';

export const MyComponent = ({ value }: { value: number }) => {
	return <my-context-provider>
		{...}
		<script type="application/json" data-hydration>
			{stringifyTyped({ value })}
		</script>
	</my-context-provider>;
};  

Once you have a context provider, all the children of the provider will have access to the context. Please note that the provider must be a parent of the consumer.

Here you can find the documentation related to the context consumer.

<my-element-provider>
  	<my-element-consumer></my-element-consumer>
</my-element-provider>

If for any reason you don't want to use the `@provideContext` decorator, you can use the `ContextProvider` component directly.

@customElement("my-context")
export class MyElement extends RadiantElement {
	provider = new ContextProvider<typeof myContext>(this, {
		context: myContext,
		initialValue: { value: "Hello World" },
	});
}