Created
July 19, 2023 14:54
-
-
Save rsmithlal/23853772375a6d89bbee3604848fe7c8 to your computer and use it in GitHub Desktop.
Create and subscribe to Rails API Action Cable for notification on Vue.js 2 app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app/javascript/channels/notification.js | |
import consumer from "./consumer"; | |
consumer.subscriptions.create({ channel: "NotificationChannel" }, { | |
connected() { | |
console.log("Connected to the notification channel"); | |
}, | |
disconnected() { | |
console.log("Disconnected from the notification channel"); | |
}, | |
received(data) { | |
console.log("Received notification:", data); | |
// Handle the notification data in your Vue.js application | |
} | |
}); | |
// In the above code, we're creating a consumer object and subscribing to the NotificationChannel. | |
// The received function will be called whenever a new notification is broadcasted to the channel. | |
// You can handle the notification data according to your requirements within the received function. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/channels/notification_channel.rb | |
class NotificationChannel < ApplicationCable::Channel | |
def subscribed | |
stream_from "notifications_#{current_user.id}" | |
end | |
def unsubscribed | |
# Any cleanup needed when the channel is unsubscribed | |
end | |
def send_notification(data) | |
ActionCable.server.broadcast("notifications_#{current_user.id}", data) | |
end | |
end | |
# In the above code, we define a NotificationChannel class that inherits from ApplicationCable::Channel. | |
# In the subscribed method, we're subscribing the current user to a specific channel named "notifications_<user_id>". | |
# This allows Action Cable to broadcast notifications to that specific channel. The unsubscribed method can be used for | |
# any cleanup tasks when the channel is unsubscribed. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/routes.rb | |
Rails.application.routes.draw do | |
# ... | |
mount ActionCable.server => '/cable' | |
# ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment