cpunion/react-actioncable-provider

Declare Consumer Cable inside Component Lifecycle Method

LouisJS opened this issue · 6 comments

I need to pass URL parameter for createConsumer to authenticate myself such as :
ws://10.67.1.175:3000/cable?access-token=atokenhere&client=someclientcode&uid=thisisauid.

These infos are in my AsyncStorage (Using expo), so i think i can only retrieve these infos in my React-native component lifecycle method.

So i'm not able to declare my consumer as global var such as :
const cable = RNActionCable.createConsumer("ws://10.67.1.175:3000/cable");

How can i include my createConsumer consumer call in my React Native Class Component.

Currently can't create a provider without consumer. But you can do it yourself like the following.

class MyContainer extends React.Component {
  static childContextTypes = {
    cable: PropTypes.object
  }

  state = {
    cable: null
  }
  
  getChildContext() {
    return {
      cable: this.state.cable
    }
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        cable: RNActionCable.createConsumer('ws://xxxxxxx')
      })
    }, 2000)
  }

  render() {
    return (
      <Child />
    )
  }
}

class Child extends React.Component {
  static contextTypes = {
    cable: PropTypes.object
  }

  render() {
    return (
      <View>
        {this.context.cable && (             // <------------ Check cable is available
          <ActionCable channel={xxx} />
        )}
      </View>
    )
  }
}

Updated, must call setState to trigger update in the example.

I have an error with

static childContext {
    cable: PropTypes.object
 }

SyntaxError.

Updated .

Succeed. Thanks for the help 💪

Hi @cpunion, how to do that with more sophisticated way?