0

I'm trying to get a little red notifications circle to update dynamically in my Rails chat application using Action Cable. The problem is that sometimes when a message is sent, it seems to trigger the receive function more than once. I'm pretty sure I have the subscriptions defined correctly, but something is going wrong.

Here I make sure to create the subscriptions using the chat_id parameter. The same parameter is used in the submitNewMessage function

assets/javascript/channels/chat.js

$(document).on('turbolinks:load', function() {

submitNewMessage();

$.ajax({
 type: "GET",
 dataType: "json",
 url: "/chats",
 success: function(data){
    $.each(data, function(i, chat){
        App['chat' + chat.id] = App.cable.subscriptions.create({
            channel: "ChatChannel",
            chat_id: chat.id}, 
            { received: function(data){

            # Code to update notifications
            }}
        });
     }
   }
});

function submitNewMessage(){
      $('#message_text').keydown(function(event) {
            if (event.keyCode == 13) {
                var text = event.target.value
                App['chat' + chat_id].send({text: text})
                $('#message_text').val(" ")
                return false;
            }
        });
}
});

And in the subscribed method I also use the chat_id params

channels/chat_channel.rb

class ChatChannel < ApplicationCable::Channel

  def subscribed
      stream_from "chat_#{param['chat_id']}_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def receive(payload)
      Message.create(user_id: current_user.id, chat_id: params["chat_id"], text: payload["text"])
  end    

end

How could the received function in chat.js be triggered more than once when a new comment is triggered?

1 Answers1

0

Turns out that the Ajax request was creating a double of each request, when I visited other pages. I fixed it by adding

if (App['chat' + chat.id] == undefined){...

before creating the subscriptions. This way it only creates a subscription if it doesn't already exist.