Stimulus, Turbolinks and Caching

Hi all,

I’m trying to figure out how to best handle Turbolinks caching and Stimulus in Rails 6. I have an index page where I load user-specific content for each item. I call the fetch method in Stimulus’ connect(), and this method again is called if I revisit the page after navigating away. This results in “flashing” since the cached page is served first, then a fresh page is fetched from the server (which means the user-specific content disappears briefly), then Stimulus connect() is called. I can try to fix this with a teardown in “turbolinks:before-cache” but that means the page is broken when I use my browser’s back and forth buttons, because Turbolinks doesn’t fetch a new copy in that instance.

How do people solve the issue of Turbolinks caching and updating the DOM with Stimulus? Ideally I can set a loaded=true data attribute, but that won’t work because the server-side HTML will always have to start with loaded=false. I’m trying to get rid of the “flashing”

Here’s a simplified GIF:
The div has a default a class of “spinner” which is removed when the content successfully loads. I re-apply the “spinner” class in my teardown() method.

When I press the back button, Turbolinks doesn’t make a server request, so the “spinner” remains forever (have to link to the gif since I’m limited to 1 img upload for some reason)

Maybe you want to prevent the fetch during the Turbolink preview

Here is how I do it when doing animations