cpunion/react-native-actioncable

'this.props' undefined in received method

zohaibahmeds63 opened this issue · 6 comments

Hello there,

I am using Redux for state management. I intend to call an action after the data is received via action cable, but I am unable to access this.props in the received callback method, as given in the example.

Any guidance would be extremely appreciated.

Can you try this code? modified from README.md.

componentDidMount () {
        this.subscription = this.context.cable.subscriptions.create(
            'ChatChannel',
            {
                received (data) {
                    this.props.dispatch(xxxAction())
                }
            }
        )
    }

I have tried with the following code but still props are undefined.

componentDidMount () { this.subscription = this.context.cable.subscriptions.create( 'SessionChannel', { received (data) { console.log(data) this.props.fetchSession(this.props.route.session_id); } } ) }

Any ideas about this issue?

Maybe I forgot some syntax rules.

In the object:

            {
                received (data) {
                    this.props.dispatch(xxxAction())
                }
            }

this is point to the object above, it isn't point to the component. You can save this variable first.

E.g.:

componentDidMount () {
        const self = this // <----- Save this to self
        this.subscription = this.context.cable.subscriptions.create(
            'ChatChannel',
            {
                received (data) {
                    self.props.dispatch(xxxAction())  // <---------- Use self instead of this
                }
            }
        )
    }

Thanks @cpunion it is working now 👍

Thanks for feedback.

@zohaibahmeds63 Did you solve the problem?

Yes, Thanks a lot for providing help!