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

Faceted Search with Stimulus and Turbo Frames
10 December 2024

Harness the power of Stimulus and Turbo Frames to drive a simple but powerful faceted search solution

Stimulus - Video Progress Tracker with LocalStorage
29 October 2024

Store ephemeral user state like video playback progress in localStorage

Stimulus - Image Upload Previews with `URL.createObjectURL`
17 September 2024

Create client-side previews of files using URL.createObjectURL

Cookies
essential