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 enough 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, a resource with shared options can be created by the resources middleware and passed into multiple widgets that will both share resource options, so that a pagination widget can set the page and another widget is used to render the page of items will react to the page change and fetch the new results.

MyComposedWidget.tsx

  1. import { create, tsx } from '@dojo/framework/core/vdom';
  2. import { createResourceMiddleware } from '@dojo/framework/core/middleware/resources';
  3. interface ResourceData {
  4. value: string;
  5. label: string;
  6. }
  7. const resources = createResourceMiddleware<ResourceData>();
  8. const factory = create({ resources });
  9. export default factory(function MyComposedWidget({ resources }) {
  10. const { getResource } = resources();
  11. const sharedResource = getResource({ sharedOptions: true });
  12. return (
  13. <div>
  14. <Results resource={sharedResource} />
  15. <Pagination resource={sharedResource} />
  16. </div>
  17. );
  18. });