'undefined this inside next.js arrow function method

I am attempting to call a method from a onClick event inside a class component:

export default class WhiteListOptions extends Component {

    triggerPurchase = async (buyQty) => {
        await this.props.purchaseFunction(buyQty);
    }

    render () {
        return (
                        <button onClick={_ => this.triggerPurchase("5000")} className="buy-btn">Buy Now</button>
        )
    }
}

Yet, for some reason it is treating "this" as undefined inside the function scope when I call props:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'props')

Does anyone have an idea of what's going on?



Solution 1:[1]

I think that .bind(this) is what you are looking for.

Putting .bind(this) after the function call you will force the function to use the context of the class.

export default class WhiteListOptions extends Component {

    triggerPurchase = async (buyQty) => {
        await this.props.purchaseFunction(buyQty);
    }

    render () {
        return (
                        <button onClick={_ => this.triggerPurchase.bind(this,"5000")} className="buy-btn">Buy Now</button>
        )
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matteo Guidetti