Aneh Thakur
Aneh Thakur

Reputation: 59

How to call function inside EventHandler function react native

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

Upvotes: 0

Views: 589

Answers (1)

Rishabh Bhatia
Rishabh Bhatia

Reputation: 1029

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.

Upvotes: 1

Related Questions