Last active
May 17, 2019 15:39
-
-
Save juanmanuelramallo/e7216eb9e8db1ac1739abe7e349c26ce to your computer and use it in GitHub Desktop.
Basic client action cable connection
This file contains 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
// somewhere in ./app.js | |
if (this.state.authenticated) { | |
this.cable = connectWS(accessToken, client, uid); | |
} | |
// ./channels/connection.js | |
import ActionCable from 'actioncable'; | |
import { env } from '../env_vars'; | |
export function connectWS(accessToken, client, uid) { | |
return ActionCable.createConsumer(`${env().REACT_APP_WS_URL}/?access-token=${accessToken}&client=${client}&uid=${uid}`); | |
} | |
// ./channels/messages_channel.js | |
import { truncate } from '../utils'; | |
export default class MessagesChannel { | |
constructor(props) { | |
this.props = props; | |
} | |
subscribe() { | |
const { cable } = this.props; | |
if (cable) { | |
this.messages = cable.subscriptions.create('MessagesChannel'); | |
this.messages.connected = () => this.handleConnected(); | |
this.messages.disconnected = () => this.handleDisconnected(); | |
this.messages.received = (d) => this.handleReceived(d); | |
} | |
} | |
handleConnected() { | |
// console.log('connected messagfes ws'); | |
} | |
handleDisconnected() { | |
console.log("handling disconnect"); | |
if (this.messages) { | |
const { cable } = this.props; | |
cable.subscriptions.remove(this.messages); | |
console.log("removing subscriptions"); | |
} | |
} | |
handleReceived(data) { | |
if (data.action !== 'destroy' && data.message && data.message.active) { | |
// do something (in this case it creates a notification) | |
new Notification('Nuevo mensaje!', { | |
body: truncate(data.message.message, 20) | |
}); | |
} | |
this.props.handleReceivedData(data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment