Turbo Will Call Stimulus `connect()` Twice

When you click a link to return to a page, or use your browsers back button to return to a page Turbo will render a cached preview of the page. It will then fetch an updated version of the page.

If you have a stimulus controller on the page what will happen is the controller is initialized twice. The initial cached version will load the controller and fire off the connect() method, then the page is refreshed via Turbo, the controller is disconnected, then reconnected when the DOM is updated from the Turbo update. This will fire the connect method a second time. Super annoying.

If you run into this you can detect when a Turbo preview is visible.

if (document.documentElement.hasAttribute("data-turbo-preview")) {
  // Turbo Drive is displaying a preview
}

I feel though, that this is the wrong solution and that my approach to how I am using StimulusJS controllers is inherently wrong.

Did you like this post? Let me know by sending me a message. Is there a topic you would like me to cover? Let me know about that too. I look forward to hearing from you!

Let's Connect!