Skip to content

Commit

Permalink
Add ActionCableProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
cpunion committed Jul 30, 2016
1 parent fa0af6e commit 9a219aa
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 8 deletions.
72 changes: 70 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,70 @@
# react-native-actioncable
ActionCable for react native
ActionCable for react native.

Just import `actioncable` module, and let it compatiblely with `react native`.

# Install

```
npm install --save react-native-actioncable
```

# Usage

Two ways to use `react-native-actioncable`

## Use ActionCable methods

```jsx
import ActionCable from 'react-native-actioncable'

const cable = ActionCable.createConsumer('ws://localhost:3000/cable')

// ... Other code
```

## Use ActionCableProvider

In outer container:

```jsx
import { ActionCableProvider } from 'react-native-actioncable'

export default function Container (props) {
return (
<ActionCableProvider url='ws://localhost:3000/cable'>
<MyApp />
</ActionCableProvider>
)
}
```

In some UI screen:

```jsx
import React, { Component, PropTypes } from 'react'
import ActionCable from 'react-native-actioncable'

export default class ChatRoom extends Component {
static contextTypes = {
cable: PropTypes.object.isRequired
};

componentDidMount () {
this.subscription = this.context.cable.subscriptions.create(
'ChatChannel',
{
received (date) {
console.log(data)
}
}
)
}

componentWillUnmount () {
this.subscription &&
this.context.cable.subscriptions.remove(this.subscription)
}

// ... Other code
}
```
36 changes: 30 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import React, { Component, PropTypes } from 'react'
import ActionCable from 'actioncable'

ActionCable.getConfig = () => null
ActionCable.createWebSocketURL = (url) => {
const result = url.replace(/^http/, 'ws')
console.log(result)
return result
}
ActionCable.startDebugging()
ActionCable.createWebSocketURL = (url) => url.replace(/^http/, 'ws')

const oldOpen = ActionCable.Connection.prototype.open
ActionCable.Connection.prototype.open = function () {
Expand All @@ -21,3 +17,31 @@ global.document = {
}

export default ActionCable

export class ActionCableProvider extends Component {
static propTypes = {
url: PropTypes.string.isRequired,
children: PropTypes.any
};

static childContextTypes = {
cable: PropTypes.object.isRequired
};

constructor (props, ...args) {
super(props, ...args)

this.cable = ActionCable.createConsumer(this.props.url)
}

getChildContext () {
return {
cable: this.cable
}
}

render () {
console.log(this.cable)
return this.props.children
}
}

0 comments on commit 9a219aa

Please sign in to comment.