dojo dragon main logo

Composing behavior with resources

Resources can be used in multiple widgets and the cached data will be shared. However, sharing the data is sometimes not sufficient when composing multiple "data-aware" widgets together. There are occasions that multiple widgets want to be able to share the current resource options, such that one widget can set a filter and another widget can react and render the filtered data set. This is where creating a resource with "shared options" come in. Sharing options across widgets is as simple as passing the same options to multiple widgets with along with the resource template.

Note: The widget itself can choose to ignore options that are passed with the template, this should be documented with the widget.

MyComposedWidget.tsx

import { create, tsx } from '@dojo/framework/core/vdom';
import { createResourceMiddleware } from '@dojo/framework/core/middleware/resources';

interface ResourceData {
	value: string;
	label: string;
}

const resource = createResourceMiddleware<ResourceData>();

const factory = create({ resource });

export default factory(function MyComposedWidget({ id, middleware: { resource } }) {
	const { createOptions } = resource;
	const options = createOptions(id);

	return (
		<div>
			<Results resource={resource({ template, options })} />
			<Pagination resource={resource({ template, options })} />
		</div>
	);
});