0

I implement this library https://github.com/elanic-tech/react-native-paytm in my project. I successfully get a response from Paytm inside my onPayTmResponse but now I want to send this response to the server but inside this function, I am unable to call any function or state it give me an undefined error.

componentWillMount() {
        if(Platform.OS == 'ios'){
            const { RNPayTm } = NativeModules
            const emitter = new NativeEventEmitter(RNPayTm)
            emitter.addListener('PayTMResponse', this.onPayTmResponse)
        }else{
            DeviceEventEmitter.addListener('PayTMResponse', this.onPayTmResponse)
        }

        //this.makeRemoteRequest();
}

onPayTmResponse(response) {
        // Process Response
        // response.response in case of iOS
        // reponse in case of Android

        var actual = "";
        if(Platform.OS == 'ios'){
            actual = JSON.parse(response.response);
        }else{
            actual = JSON.parse(response);
        }

        console.log(actual, this.state);

        if(actual.RESPCODE == "01"){
            // Place Order
            placeOrder();
        }else{
            alert(actual.RESPMSG);
            this.setState({loading: false, buttonText: 'Continue'});
        }
    }

Error

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Aneh Thakur
  • 59
  • 2
  • 7
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Aluan Haddad Apr 24 '18 at 01:54

1 Answers1

1

Bind your onPayTmResponse function with this inside componentWillMount like

componentWillMount() {
  this.onPayTmResponse = this.onPayTmResponse.bind(this); // note: we bind onPayTmResponse with this
  if(Platform.OS == 'ios'){
    const { RNPayTm } = NativeModules
    const emitter = new NativeEventEmitter(RNPayTm)
    emitter.addListener('PayTMResponse', this.onPayTmResponse)
  }else{
    DeviceEventEmitter.addListener('PayTMResponse', this.onPayTmResponse)
  }
  //this.makeRemoteRequest();
}

Now you should be able to call setState within onPayTmResponse.

Rishabh Bhatia
  • 1,019
  • 6
  • 14