Idiomatic way to populate a custom component

Hi there,

I was wanting to know what the idiomatic way to dynamically populate a custom component would be? For instance, say I had a sidebar in a layout that I wanted to populate with some kind of data. For example, let’s stick with device names:

  • I know that a component can read pageData if no other context is passed to it, but I don’t want each page to use a workflow to fetch the device names since it’s not always relevant
  • I don’t think I can use a custom endpoint with a wildcard since all my other endpoints would match first since they have more specific routes
  • I may have missed it in the docs, but I don’t see a way to pass a context object directly to a component

Current I’m just using JS to asynchronously fetch the data at an API endpoint and then building the elements into the DOM. If that’s “the right way to do it” that’s totally fine – I just wanted to make sure I wasn’t missing something that was preferred. Thank you!

As you’ve identified, custom data in a layout can be a challenge since it does require every page that uses the layout to query the required information.

To directly answer your question, there is no way to pass custom context to a component without a page/workflow in the middle.

An alternative approach that we took with the Connected Product Foundation (CPF) was to use Turbo Frames. The CPF itself has custom data in a layout (the nav items come from a Data Table). A turbo frame is loaded separately by requesting its own endpoint, triggering its own workflow, and rendering its own content.

The CPF’s layout is reduced to essentially:

<body>
  <turbo-frame id="cpf-element-top-nav" src="/cpf/elements/top-nav" target="_top" data-turbo-permanent></turbo-frame>
  
  <main>
    <turbo-frame id="cpf-element-nav" src="/cpf/elements/nav" target="_top" data-turbo-permanent></turbo-frame>
    {{page}}
  </main>
</body>

Those two Turbo Frames make asynchronous request to their own endpoints (e.g. /cpf/elements/nav). Those endpoints trigger workflows specifically for the content they need and render a page that contains only the markup required for that frame. This eliminates the need to query data in every page that uses the layout. The data-turbo-permanent attribute prevents the turbo frame from loading again as the user navigates around the site, which means the endpoint/workflow is only ever triggered once.

The CPF is an application template, so you can create a new application from it and explore how its implemented. There are several Turbo Frames, including the devices table, that will help point you in the right direction.