Installations
npm install @kesha-antonov/react-native-action-cable
Developer Guide
Typescript
No
Module System
ESM
Score
75.9
Supply Chain
98.2
Quality
76.8
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
CoffeeScript (91.48%)
JavaScript (8.52%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
Download Statistics
Total Downloads
384,444
Last Day
17
Last Week
3,647
Last Month
16,047
Last Year
215,302
GitHub Statistics
MIT License
57 Stars
108 Commits
25 Forks
6 Watchers
1 Branches
1 Contributors
Updated on Nov 29, 2024
Package Meta Information
Latest Version
1.1.5
Package Id
@kesha-antonov/react-native-action-cable@1.1.5
Unpacked Size
33.06 kB
Size
10.76 kB
File Count
29
Published on
Mar 02, 2024
Total Downloads
Cumulative downloads
Total Downloads
384,444
Last Day
-83.5%
17
Compared to previous day
Last Week
-17.6%
3,647
Compared to previous week
Last Month
6.9%
16,047
Compared to previous month
Last Year
123.5%
215,302
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
ActionCable + React Native
Use Rails 5+ ActionCable channels with React Native for realtime magic.
This is a fork from https://github.com/schneidmaster/action-cable-react
Overview
The react-native-action-cable
package exposes two modules: ActionCable, Cable.
ActionCable
: holds info and logic of connection and automatically tries to reconnect when connection is lost.Cable
: holds references to channels(subscriptions) created by action cable.
Install
yarn add @kesha-antonov/react-native-action-cable
Usage
Import:
1import { 2 ActionCable, 3 Cable, 4} from '@kesha-antonov/react-native-action-cable'
Define once ActionCable and Cable in your application setup in your store (like Redux
or MobX
).
Create your consumer:
1const actionCable = ActionCable.createConsumer('ws://localhost:3000/cable')
Right after that create Cable instance. It'll hold info of our channels.
1const cable = new Cable({})
Then, you can subscribe to channel:
1const channel = cable.setChannel( 2 `chat_${chatId}_${userId}`, // channel name to which we will pass data from Rails app with `stream_from` 3 actionCable.subscriptions.create({ 4 channel: 'ChatChannel', // from Rails app app/channels/chat_channel.rb 5 chatId, 6 otherParams... 7 }) 8) 9 10channel 11 .on( 'received', this.handleReceived ) 12 .on( 'connected', this.handleConnected ) 13 .on( 'rejected', this.handleDisconnected ) 14 .on( 'disconnected', this.handleDisconnected )
...later we can remove event listeners and unsubscribe from channel:
1const channelName = `chat_${chatId}_${userId}` 2const channel = cable.channel(channelName) 3if (channel) { 4 channel 5 .removeListener( 'received', this.handleReceived ) 6 .removeListener( 'connected', this.handleConnected ) 7 .removeListener( 'rejected', this.handleDisconnected ) 8 .removeListener( 'disconnected', this.handleDisconnected ) 9 channel.unsubscribe() 10 delete( cable.channels[channelName] ) 11} 12
You can combine React's lifecycle hook useEffect
to subscribe and unsubscribe from channels. Or implement custom logic in your store
.
Here's example how you can handle events:
1function Chat ({ chatId, userId }) { 2 const [isWebsocketConnected, setIsWebsocketConnected] = useState(false) 3 4 const onNewMessage = useCallback(message => { 5 // ... ADD TO MESSAGES LIST 6 }, []) 7 8 const handleReceived = useCallback(({ type, message }) => { 9 switch(type) { 10 'new_incoming_message': { 11 onNewMessage(message) 12 } 13 ... 14 } 15 }, []) 16 17 const handleConnected = useCallback(() => { 18 setIsWebsocketConnected(true) 19 }, []) 20 21 const handleDisconnected = useCallback(() => { 22 setIsWebsocketConnected(false) 23 }, []) 24 25 const getChannelName = useCallback(() => { 26 return `chat_${chatId}_${userId}` 27 }, [chatId, userId]) 28 29 const createChannel = useCallback(() => { 30 const channel = cable.setChannel( 31 getChannelName(), // channel name to which we will pass data from Rails app with `stream_from` 32 actionCable.subscriptions.create({ 33 channel: 'ChatChannel', // from Rails app app/channels/chat_channel.rb 34 chatId, 35 otherParams... 36 }) 37 ) 38 39 channel 40 .on( 'received', handleReceived ) 41 .on( 'connected', handleConnected ) 42 .on( 'disconnected', handleDisconnected ) 43 }, []) 44 45 const removeChannel = useCallback(() => { 46 const channelName = getChannelName() 47 48 const channel = cable.channel(channelName) 49 if (!channel) 50 return 51 52 channel 53 .removeListener( 'received', handleReceived ) 54 .removeListener( 'connected', handleConnected ) 55 .removeListener( 'disconnected', handleDisconnected ) 56 channel.unsubscribe() 57 delete( cable.channels[channelName] ) 58 }, []) 59 60 useEffect(() => { 61 createChannel() 62 63 return () => { 64 removeChannel() 65 } 66 }, []) 67 68 return ( 69 <View> 70 // ... RENDER CHAT HERE 71 </View> 72 ) 73} 74
Send message to Rails app:
1cable.channel(channelName).perform('send_message', { text: 'Hey' }) 2 3cable.channel('NotificationsChannel').perform('appear')
Methods
ActionCable
top level methods:
.createConsumer(websocketUrl, headers = {})
- create actionCable consumer and start connecting.websocketUrl
- url to your Rails app'scable
endpointheaders
- headers to send with connection request
.startDebugging()
- start logging.stopDebugging()
- stop logging
ActionCable
instance methods:
.open()
- try connect.connection.isOpen()
- check ifconnected
.connection.isActive()
- check ifconnected
orconnecting
.subscriptions.create({ channel, otherParams... })
- create subscription to Rails app.disconnect()
- disconnects from Rails app
Cable
instance methods:
.setChannel(name, actionCable.subscriptions.create())
- set channel to get it later.channel(name)
- get channel by name
channel
methods:
.perform(action, data)
- send message to channel. action -string
, data -json
.removeListener(eventName, eventListener)
- unsubscribe from event.unsubscribe()
- unsubscribe from channel.on(eventName, eventListener)
- subscribe to events. eventName can bereceived
,connected
,rejected
,disconnected
or value ofdata.action
attribute from channel message payload.
Custom action example:
1{ 2 "identifier": "{\"channel\":\"ChatChannel\",\"id\":42}", 3 "command": "message", 4 "data": "{\"action\":\"speak\",\"text\":\"hello!\"}" 5}
Above message will be emited with eventName = 'speak'
Contributing
- Fork it ( https://github.com/kesha-antonov/react-native-action-cable/fork )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create a new Pull Request
Credits
Obviously, this project is heavily indebted to the entire Rails team, and most of the code in lib/action_cable
is taken directly from Rails 5. This project also referenced fluxxor for implementation details and props binding.
License
MIT

No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE.txt:0
- Info: FSF or OSI recognized license: MIT License: LICENSE.txt:0
Reason
3 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-4vvj-4cpr-p986
Reason
Found 5/24 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 11 are checked with a SAST tool
Score
2.9
/10
Last Scanned on 2025-02-10
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More