Stimulus - Orchestrate Complex UI Changes with Target Callbacks

Use Stimulus target callbacks to dynamically update parts of your UI

View Solution on Patreon
Stimulus - Orchestrate Complex UI Changes with Target Callbacks

Premise

The Hotwire mantra is to precalculate HTML on the server and send it over to the client in fully assembled form - a “white glove” service, so to speak. Many developers I’ve met go to great lengths to even orchestrate every smallest UI change with tiny Turbo Stream fragments in pursuit of a “no JS” app.

🌶️ However, sometimes all the information you need to update your UI is already there in the DOM. In such cases, using server-side rendered HTML changes feels like breaking a fly on a wheel. Not only will it consume precious CPU time on your servers, it also requires you to preserve and manage state somehow. In many cases like the present one, when those UI changes are only ephemeral, this is clearly overshooting the target.

Starting Point

In Challenge 18, we used Stimulus’ Outlets API to solve a similar problem. We are going to take a bit of a different take on this: As jobs come in via Websockets, we want to use simple client-size logic to count and categorize them.

The setup goes like this:

  • On the server, we emulate jobs being appended and removed to the job-list <ul> via Websockets, similar to what broadcast_append_to does:

https://stackblitz.com/edit/hotwire-club-stimulus-target-callbacks?file=index.js%3AL69

https://stackblitz.com/edit/hotwire-club-stimulus-target-callbacks?file=index.html%3AL48

The appended <li> elements are itemTargets of the global Stimulus job-list-controller.

  • index.html contains 4 statistics areas for the total count, and counts for the respective job types, each of them is its own Stimulus target:

https://stackblitz.com/edit/hotwire-club-stimulus-target-callbacks?file=index.html%3AL60

Challenge

Using Target Callbacks, update the counts in the statistics sidebar:

Here’s a preview of the end result:

An example of a dashboard of async jobs being processed

Teaser

We are using custom data-job-type attributes to discern the respective count targets. How could we make that more idiomatic Stimulus?

More from

Stimulus - Picture in Picture API
04 June 2024

Use an IntersectionObserver to trigger a Picture in Picture overlay

Stimulus - Progressive Image Loading with Blurhash
23 April 2024

Improve Largest Contentful Paint using image blurhashes and Stimulus

Hotwire Combobox with Real Time Data
12 March 2024

Update combobox options using Websockets and Stimulus outlets

essential