cpunion / react-native-actioncable

[Unmaintained] ActionCable for react native
MIT License
59 stars 16 forks source link

'this.props' undefined in received method #1

Closed zohaibahmeds63 closed 7 years ago

zohaibahmeds63 commented 8 years ago

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.

cpunion commented 8 years ago

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

componentDidMount () {
        this.subscription = this.context.cable.subscriptions.create(
            'ChatChannel',
            {
                received (data) {
                    this.props.dispatch(xxxAction())
                }
            }
        )
    }
tauqeer-ahmad commented 7 years ago

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?

cpunion commented 7 years ago

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
                }
            }
        )
    }
tauqeer-ahmad commented 7 years ago

Thanks @cpunion it is working now 👍

cpunion commented 7 years ago

Thanks for feedback.

@zohaibahmeds63 Did you solve the problem?

zohaibahmeds63 commented 7 years ago

Yes, Thanks a lot for providing help!