Rafael Castro
Rafael Castro

Reputation: 609

Disconnect and unsubscribe Action Cable on Rails 6

This was already asked here, but it seems that the old methods (example and example) no longer work on Rails 6 because you cannot use App.channel inside your app/javascript/channels/your_channel.js. Though, correct me if I'm wrong because I'm new to Rails.

My question is: how to disconnect or/and unsubscribe from client side on Rails 6?

I'm especially interested in the "on page change" scenario.

Upvotes: 4

Views: 4385

Answers (2)

alfakini
alfakini

Reputation: 4757

Based on what you shared with us, I imagine you are trying to remove a subscription. You can remove it using consumer.subscriptions.remove [1].

Could you share the snippet of code you have in your app/javascript/channels/your_channel.js?

Upvotes: 3

Rafael Castro
Rafael Castro

Reputation: 609

The solution was to save the subscription on a this variable and do the remove call if this variable is not null when page loads, then do the new subscription.

// File: app/javascript/channels/your_channel.js
import consumer from "./consumer";

$(document).on('turbolinks:load', function() {
    if (this.subscription) {
        consumer.subscriptions.remove(this.subscription);
        console.log("unsubing");
    }

    if ($('#hashtag').attr('data-hashtag-id')) {
        var subscription = consumer.subscriptions.create({channel: "TweetsChannel", id: $('#hashtag').attr('data-hashtag-id')}, {
            connected() {
                console.log("we are live on: " + $('#hashtag').attr('data-hashtag-id'));
            },

            disconnected() {
                console.log("disconecting")
            },

            received(data) {
                $('#tweets-card').prepend(data.content)
            }
        });

        this.subscription = subscription;
    }
});

Upvotes: 3

Related Questions