Turbo Streams - Custom Stream Actions - LocalStorage

Store ephemeral state changes locally using localStorage and custom Turbo Stream Actions.

View Solution on Patreon
Turbo Streams - Custom Stream Actions - LocalStorage

Premise

Looking back at Challenge 13, there’s a nice UX adjustment we could make: Currently, reloading the browser results in jumping back to the first video in the list. However, assuming a user watches all videos top to bottom, she probably doesn’t want to have to remember the last watched video herself. We can solve this by putting the currently watched video into localStorage, and jump to this video on refresh.

Starting Point

We start from a fork of Challenge 13 where I have added additional placeholders for our logic to go.

Challenge

To solve this challenge we need four things:

  • a <template> in the DOM to hold our new custom Turbo Stream action. I’ve already prepared this here.
  • the actual logic for the action. Please add it here.
  • execution of this logic (i.e., appending a cloned <turbo-stream> tag to the DOM. This is best done after the video has changed.
  • restore the last watched video in a new DOMContentLoaded event listener.

Below is a screen capture of the end result:

Video playlist management

Caveat

Using this technique you might get a flicker showing the first video before jumping to the stored one. What can you do to mitigate this?

More from

Hotwire Combobox with Real Time Data
12 March 2024

Update combobox options using Websockets and Stimulus outlets

Turbo Streams - Custom Stream Actions - Video Playlist Management
10 October 2023

Managing a video playlist using custom Turbo Stream Actions.

Turbo Streams - Custom Stream Actions
15 August 2023

Use custom Turbo Stream actions to orchestrate complex UI animations.

Cookies
essential