hotwired / stimulus

A modest JavaScript framework for the HTML you already have
https://stimulus.hotwired.dev/
MIT License
12.55k stars 420 forks source link

Turbolinks duplicated requests #148

Closed mbajur closed 6 years ago

mbajur commented 6 years ago

Hello!

I'm playing around with Stimulus and i encountered a pretty bad blocker - each time i leave and get back to a page which uses stimulus controller, all the controller code gets duplicated. One reload = one replica.

My controller periodically fetches stats and going to a different page and getting back on stats page 10 times makes the request duplicated 10 times - that's pretty bad.

You can see it here: https://mastodon-tags-explorer.hcxp.co/stats

Click on the Instances link and then again at Stats - you'll see that request to /stats.json is triggered two times per 10 seconds while it should be triggered once. Source code of this app is here: https://github.com/mbajur/mastodon-tags-explorer

Thanks in advance for any clues!

alealvb commented 6 years ago

Hey!, the stimulus controllers are not persisted through the visits of your page, every time you visit a page with a data-controller, stimulus will instantiate a new controller and when you leave it will disconnect it, I think your issue is that you are using setInterval with Turbolinks that keeps the js through the visits. try using clearInterval on the disconnect of your controller

javan commented 6 years ago

That's correct. Your controller starts a timer on connect(), but doesn't stop it on disconnect() so it continues running. See https://stimulusjs.org/handbook/working-with-external-resources#releasing-tracked-resources.