Search code examples
ruby-on-railsactioncablestimulusjsview-componentsstimulus-reflex

How can I use a Custom Channel of Action Cable with Stimulus Reflex and View Component?


So, I'm working on a project that should have a chat component same as the linkedin chat, where the user will have all their contacts and messages.

But, I've tried of all ways to work with stimulus_reflex and view_component to create this chat_box, but until now I had none progress.

So right now I'm trying to create a chat with pure action_cable, but my doubt is: Can I use this action_cable channel ('ChatRoom') with Stimulus Reflex? Because when we see the rails console shows something like this: Broadcasting to StimulusReflex::Channel:1, and I want to Broadcast to the ChatRoom Channel.

Someone was tried the same?


Solution

  • stimulus_reflex will use its own channel to update the page after a reflex. But those updates happen automatically and only for the user that triggered the reflex. Generally you don't want to touch those parts.

    If you want to broadcast a message or a dom transformation after a reflex, you can do so by using cable_ready (which comes included with stimulus_reflex.

    So something like this could work for you:

    def my_reflex
      @chat = Chat.find(element.dataset[:chat_id])
      message = @chat.message.create(message: element.value)
      cable_ready["chatroom-#{@chat.id}"]. insert_adjacent_html(
        selector: "#chat",
        position: "beforeEnd",
        html: ApplicationController.render(ChatMessageComponent.new(message: message))                     
      )
    end
    

    For more possibilties you can check out the cable_ready documentation