Premise
A lot of UX leverage lies in the way applications manage ephemeral user state.
The traditional approach to store such data would be to reach for server side sessions. However, sometimes this is overshooting the target because it leads to more complexity on the server side, having to (de)serialize data structures and manage rehydration. Often, client-side localStorage
provides a simpler alternative.
Starting Point
We are going to experiment with localStorage
using an example containing three <video>
elements on a page:
https://stackblitz.com/edit/stimulus-video-progress-tracker?file=index.html%3AL41
The goal is to store the playing progress for each video and restore it on page reload. Here’s a GIF showing this in action:
Challenge
In a video-progress
Stimulus controller, write two actions:
recordProgress
for storing the current time for each video inlocalStorage
#seekToProgress
to restore the current time uponconnect
As you can see, #seekToProgress
is already called whenever the controller is connected. What’s missing is to fire the correct event and update the storage entry. For this, wire up it up in data-action
:
https://stackblitz.com/edit/stimulus-video-progress-tracker?file=index.html%3AL49
Tip: Look at the Video Embed element docs for some clues.
Teasers
Suppose you want to store sensitive data in localStorage
that you don’t want anyone to tamper with. What are your options?