Rails ActionCable and React Native
I'm working on a companion React Native app to accompany my RoR webapp, and want to build a chat feature using ActionCable (websockets). I cannot get my React Native app to talk to ActionCable.
I have tried a number of libraries including react-native-actioncable with no luck. The initial connection seems to be working (I know this because I was having errors before and they've since gone away when I passed the proper params).
This is an abbreviated version of my React Native code:
import ActionCable from 'react-native-actioncable'
class Secured extends Component {
componentWillMount () {
var url = 'https://x.herokuapp.com/cable/?authToken=' + this.props.token + '&client=' + this.props.client + '&uid=' + this.props.uid + '&expiry=' + this.props.expiry
const cable = ActionCable.createConsumer(url)
cable.subscriptions.create('inbox_channel_1', {
received: function (data) {
console.log(data)
}
})
}
render () {
return (
<View style={styles.container}>
<TabBarNavigation/>
</View>
)
}
}
const mapStateToProps = (state) => {
return {
email: state.auth.email,
org_id: state.auth.org_id,
token: state.auth.token,
client: state.auth.client,
uid: state.auth.uid,
expiry: state.auth.expiry
}
}
export default connect(mapStateToProps, { })(Secured)
Anyone with more experience connecting ActionCable to React Native and can help me out?
The url endpoint you're attaching to is not a websocket, so that's probably your issue. The example app they've listed was updated just 2 months ago and is based on RN 0.48.3, so I have to guess that it probably still works. Have you tried cloning and running it?
Looks like you'll also need to setup a provider as well (<ActionCableProvider>)
import RNActionCable from 'react-native-actioncable';
import ActionCableProvider, { ActionCable } from 'react-actioncable-provider';
const cable = RNActionCable.createConsumer('ws://localhost:3000/cable');
class App extends Component {
state = {
messages: []
}
onReceived = (data) => {
this.setState({
messages: [
data.message,
...this.state.messages
]
})
}
render() {
return (
<View style={styles.container}>
<ActionCable channel={{channel: 'MessageChannel'}} onReceived={this.onReceived} />
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<View>
<Text>There are {this.state.messages.length} messages.</Text>
</View>
{this.state.messages.map((message, index) =>
<View key={index} style={styles.message}>
<Text style={styles.instructions}>
{message}
</Text>
</View>
)}
</View>
)
}
}
export default class TestRNActionCable extends Component {
render() {
return (
<ActionCableProvider cable={cable}>
<App />
</ActionCableProvider>
);
}
}
Comments
Post a Comment