Skip to content

Instantly share code, notes, and snippets.

@jwo
Last active February 14, 2022 13:32
Show Gist options
  • Save jwo/a23d8123d168cb432c2fdc4922e2ecf6 to your computer and use it in GitHub Desktop.
Save jwo/a23d8123d168cb432c2fdc4922e2ecf6 to your computer and use it in GitHub Desktop.
Notes before I blog about it: how-to-use-actioncable-and-npm-action-cable
import React, { Component } from 'react';
import ActionCable from 'actioncable';
class App extends Component {
componentWillMount() {
var cable = ActionCable.createConsumer('ws://localhost:3000/cable')
cable.subscriptions.create('CartChannel', {
received(data){
console.log("CartChannel received data", data)
}
});
cable.subscriptions.create('ProductChannel', {
received(data){
console.log("ProductChannel received data", data)
}
});
}
render() {
return (
<div className="App">
<p>Check the console log</p>
</div>
);
}
}
export default App;

Getting this to work wasn't the easiest of processes. I wasted a bit of time using the incorrect actioncable npm package. The correct one is https://www.npmjs.com/package/actioncable.

In Rails, you need to add the following to allow connections from not-port-3000 in development mode:

# config/initializers/cable.rb 

if Rails.env.development?
  Rails.application.config.action_cable.allowed_request_origins = ['http://localhost:5000', 'http://localhost:3000']
end

Notes:

  1. I'm using create-react-app
  2. You npm install actioncable --save to install the correct actioncable package. Do not install action-cable by mistake.
  3. You can run it on not-port 3000 by PORT=5000 npm start
  4. I'm not authenticating the user at all; Rails wants you to do this with signed cookies, but this would be more difficult with auth tokens, etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment