I’ve stumbled across problem where my Stimulus controller was connected / disconnected and connected again on page entry. This is happening in following situation where response to GET request sends back “redirect” response. Then on this new page - your controller will connect and then quickly disconnect.
If I change this request to POST and then send back redirect - it correctly connects only once on next page.
Thank you in advance for help / explanation of why it should work like this?
Taking a wild guess, but if the page redirected to was recently visited and cached in turbo then you might see this behavior. When navigating to turbo cached page, the cached version loads (executing any stimulus controllers) while fetching the same page from the server. When the page from the server replaces the cached one, the controllers from the cached page execute disconnect as the DOM is removed and the new DOM executes the the new stimulus connect methods.
Turbo clears it’s cache when executing non-GET requests (e.g. POST) because something the backend state. This might be why you do not see the same behavior when using POST.
See: Navigate with Turbo Drive
you can use turbo events to handle conditionally that js logic. Turbo Reference
Thank you for suggestion but that’s not the case. I have been turning off preview behaviour. The only thing that helped was when I mark link as “turbo: false”.