TypeError: “FunctionName” is not a function async and await - React Native

Viewed 134

I'm trying to call the _addToOrder function but Error:

[TypeError: this._addToOrder is not a function. I am getting (In 'this._addToOrder ()', 'this._addToOrder' is undefined)]

I extract data from the webview with onMessage. According to the incoming data, I have to call the _addToOrder function.

class PayWtihOnlineModal extends Component {


     onMessage ( event ) {
     try {
     if (event.nativeEvent.data == "tamam") 
              this._addToOrder();
     }
        } catch (err) {
          // handle errors
        }
        }
    
     _addToOrder = async () => {
     try {
       await  this.props.BasketStore.setOrder(...);
        } catch (err) {
          // handle errors
        }
      }
}

export default PayWtihOnlineModal;
1 Answers

You have to bind this to onMessage in the class constructor function or use the arrow function instead.

Something like this:

class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log('Click happened');
  }

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

or:

class Foo extends Component {
  const handleClick() = () => {
    console.log('Click happened');
  }

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

For more you can visit react docs.

Related