Custom Turbo Stream Actions Discussion
Great episode! Is there any convention or recommendation for managing the JS code instead of throwing it all in the application.js
? Something like app/javascript/stream_actions/console_log.js
, etc, and then having an import statement that loads the entire folder?
You sure can do that. I would have each file register the function itself and all you'd need to is require those files.
I see you're importing from @hotwired/turbo
I have Rails 7 set up with importmaps so have the pin pin '@hotwired/turbo-rails', to: 'turbo.min.js'
however trying import { StreamActions } from '@hotwired/turbo-rails'
just results in the error: Uncaught SyntaxError: The requested module '@hotwired/turbo-rails' does not provide an export named 'StreamActions'
I've seen multiple different ways of solving the problem and even using something like turbo-power but what would be the recommended way of setting up the pins/imports/etc for a simple example like the console_log custom action?
Hi Ben, did you find an answer to this question? I have the same situation.
I am going to follow this: https://github.com/hotwired/turbo-rails/issues/441
Hi Neil, I left the pins as stated above and eventually found a nice simple way of using the Turbo
object created via import '@hotwired/turbo-rails'
:
Turbo.StreamActions.redirect = function () {
const url = this.getAttribute('url') || '/'
Turbo.visit(url, { frame: '_top', action: 'advance' })
}
To round it out we created a quick helper as well:
module TurboStreams::RedirectHelper
def redirect(url)
turbo_stream_action_tag("redirect", url: url)
end
end
Turbo::Streams::TagBuilder.prepend(TurboStreams::RedirectHelper)
render turbo_stream: turbo_stream.redirect(root_url)
(it's essentially the same solution as in the link you posted)
Hi Chris, do you have plans to make a video on using turbo in rails 7 like we use ajax in older rails versions with rails UJS ?
Great episode, that really seems cool and easy to approach. Yes, I'd love to see more episodes on Turbo, frames and streams