Implementing a Data Store

Implement a data store in this lesson.

Observing and responding to changes

If we want to use the DOM as a place to hold on to the state of the client-side system, it’s helpful to know when that state changes. In a Hotwire system, where new HTML text might be added to the DOM as a result of a form submission or an ActionCable text receipt, detecting that HTML change and performing an action based on it allows for much useful behavior while keeping the drawing logic on the server-side.

MutationObserver API

We can do this by using the MutationObserver API, which is a standard part of every contemporary browser. Stimulus itself is powered by MutationObserver calls, so any browser that can run Stimulus can manage MutationObservers. Browsers that are older than, say, Internet Explorer 11 need the @stimulus/polyfill package to run. For our purposes, we’re going to use a MutationObserver object to solve a minor problem on our schedule page. When we list the user’s favorite concerts, we want that list to be sorted by the date of the concert. The problem is that, even if we sort the initial server-side list, we can only append new favorites as they come in via Turbo Stream. What we want is to have them go into the list in their correctly sorted place. To do this, we’re going to use the MutationObserver API to build a generic Stimulus controller that will sort its internal targets whenever a new target is added.

This code is a simplified version of what uses to sort emails when they are added back into the “already seen” list.

The logic here is:

  1. Detect when a new item has been added to the list, and then
  2. Ensure the item list is properly sorted.

To make this work, we need to make some minor changes in the ERB file for the favorite list. Specifically, we need to make some changes to the list of favorites:

Get hands-on with 1200+ tech skills courses.