How to connect Ruby on Rails 6 ActionCable to Frontend (React Native & VueJS)


I’m trying to create a live chat app using Ruby on Rails 6 with ActionCable.

So, I have ChatChannel to get update, if there has a new room chat.

class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from 'chat_index'
    # stream_from "some_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

That it’s for the backend.

For the frontend, I’m trying with React Native, I searched for a package to help me to connect with ActionCable and I founded react-actioncable-provider. I tried to install the package and it’s always end with error, I check from the github repository, someone said that the package is not maintained anymore. So, I go to the second package and it was react-native-action-cable. After I installed, I tried to follow the documentation. But when I tried to connect and received data it wasn’t working. Here is my code in frontend :

import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {ActionCable, Cable} from '@kesha-antonov/react-native-action-cable';

const App = () => {
  const actionCable = ActionCable.createConsumer(
    'ws://api.wefix.gibahin.team/cable',
  );

  const cable = new Cable({});

  const channel = cable.setChannel(
    `chat_index`, // channel name to which we will pass data from Rails app with `stream_from`
    actionCable.subscriptions.create({
      channel: 'ChatChannel', // from Rails app app/channels/chat_channel.rb
    }),
  );

  channel
    .on('received', data => console.log(data))
    .on('connected', () => console.log('connected'));

  return (
    <View>
      <Text>Test</Text>
    </View>
  );
};

export default App;

const styles = StyleSheet.create({});

I tried it using Rails Console to broadcast a Chat :
enter image description here
I was expected I will received LOG "connected" and LOG "the chat object" in my React Native terminal, but there was no any log.

And my last question, Is anyone can recommend me some package that I can use for my React Native and Vue.js to connect to my backend ActionCable ? It seem that the second package that I was used now in my React Native is also not maintained again.

Source: Vue – Stack Overflow

November 10, 2021
Category : News
Tags: actioncable | react native | ruby-on-rails | ruby-on-rails-6 | Vue.js

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.