npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kesha-antonov/react-native-action-cable

v2.0.0

Published

Connect React Native apps to Rails ActionCable for real-time bidirectional communication.

Downloads

8,362

Readme


✨ Features

  • 🔌 WebSocket Connection - Automatic connection management with reconnection support
  • 📡 Channel Subscriptions - Subscribe to multiple ActionCable channels
  • 🔄 Auto-Reconnect - Automatically reconnects when connection is lost
  • 🔐 Custom Headers - Support for authentication and dynamic headers
  • 📱 React Native Ready - Works without window object polyfills
  • 🛡️ Connection Reuse - Prevent duplicate connections during hot reloads
  • TypeScript - Full TypeScript support included

📖 Table of Contents


📦 Installation

Yarn

yarn add @kesha-antonov/react-native-action-cable

npm

npm install @kesha-antonov/react-native-action-cable

🚀 Quick Start

1. Create a consumer

import { ActionCable, Cable } from '@kesha-antonov/react-native-action-cable'

const actionCable = ActionCable.createConsumer('ws://localhost:3000/cable')
const cable = new Cable({})

2. Subscribe to a channel

const channel = cable.setChannel(
  'ChatChannel',
  actionCable.subscriptions.create({
    channel: 'ChatChannel',
    roomId: 1
  })
)

channel
  .on('received', (data) => console.log('Received:', data))
  .on('connected', () => console.log('Connected!'))
  .on('disconnected', () => console.log('Disconnected'))

3. Send messages

channel.perform('send_message', { text: 'Hello!' })

4. Cleanup

channel.unsubscribe()

📚 API Reference

ActionCable

| Method | Description | |--------|-------------| | createConsumer(url, headers?) | Create a new consumer and connect | | getOrCreateConsumer(url, headers?) | Reuse existing consumer or create new one | | disconnectConsumer(url) | Disconnect and remove consumer from cache | | startDebugging() | Enable debug logging | | stopDebugging() | Disable debug logging |

Consumer Instance

| Method | Description | |--------|-------------| | subscriptions.create(params) | Create a channel subscription | | connection.isOpen() | Check if connected | | connection.isActive() | Check if connected or connecting | | disconnect() | Disconnect from server |

Cable

| Method | Description | |--------|-------------| | setChannel(name, subscription) | Register a channel | | channel(name) | Get channel by name |

Channel

| Method | Description | |--------|-------------| | on(event, callback) | Subscribe to events: received, connected, disconnected, rejected, error | | removeListener(event, callback) | Remove event listener | | perform(action, data) | Send message to server | | unsubscribe() | Unsubscribe from channel |


⚙️ Advanced Usage

// Static headers
const actionCable = ActionCable.createConsumer('ws://localhost:3000/cable', {
  'Authorization': 'Bearer token123'
})

// Dynamic headers (re-evaluated on each connection)
const actionCable = ActionCable.createConsumer('ws://localhost:3000/cable', () => ({
  'Authorization': `Bearer ${getAuthToken()}`
}))

Use getOrCreateConsumer to prevent duplicate connections during hot reloads:

// ❌ Creates new connection every time
const actionCable = ActionCable.createConsumer('ws://localhost:3000/cable')

// ✅ Reuses existing connection
const actionCable = ActionCable.getOrCreateConsumer('ws://localhost:3000/cable')
channel.on('error', (error) => {
  console.log('Connection error:', error)
  // Handle: no internet, wrong URL, server down, auth failure
})
function useActionCable(channelName: string, params: Record<string, unknown>) {
  const [connected, setConnected] = useState(false)

  useEffect(() => {
    const channel = cable.setChannel(
      channelName,
      actionCable.subscriptions.create({ channel: channelName, ...params })
    )

    channel
      .on('connected', () => setConnected(true))
      .on('disconnected', () => setConnected(false))
      .on('received', handleReceived)

    return () => {
      channel.removeListener('received', handleReceived)
      channel.unsubscribe()
      delete cable.channels[channelName]
    }
  }, [channelName])

  return { connected, channel: cable.channel(channelName) }
}

Messages with data.action attribute are emitted as separate events:

# Rails sends:
{ action: 'speak', text: 'hello!' }
// React Native receives:
channel.on('speak', (data) => {
  console.log(data.text) // 'hello!'
})

🧪 Testing

Jest Mock

jest.mock('@kesha-antonov/react-native-action-cable', () => ({
  ActionCable: {
    createConsumer: jest.fn(() => ({
      subscriptions: {
        create: jest.fn(() => ({
          on: jest.fn().mockReturnThis(),
          removeListener: jest.fn().mockReturnThis(),
          perform: jest.fn(),
          unsubscribe: jest.fn(),
        })),
      },
      connection: {
        isActive: jest.fn(() => true),
        isOpen: jest.fn(() => true),
      },
      disconnect: jest.fn(),
    })),
  },
  Cable: jest.fn(() => ({
    channels: {},
    channel: jest.fn(),
    setChannel: jest.fn(),
  })),
}))

See examples/testing for complete testing examples.


📂 Examples

| Example | Description | |---------|-------------| | Complete Chat App | Full Rails backend + React Native frontend | | Apollo GraphQL | ActionCable with GraphQL subscriptions | | Testing | Jest mocks and testing patterns |


🤝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

👏 Credits

Based on action-cable-react. Code in lib/action_cable is adapted from Rails ActionCable.

Please note that this project is maintained in free time. If you find it helpful, please consider becoming a sponsor.


📄 License

MIT