javascriptreactjschargebee

ChargeBee Drop-in checkout + React: Error


I'm trying to add the drop-in checkout to a react SPA, following https://www.chargebee.com/checkout-portal-docs/drop-in-tutorial.html#implementation. I'm dynamically adding chargebee.js after the rest of the view gets rendered, and then call registerAgain().

componentDidMount() {
    const el = document.createElement('script');
    el.onload = () => {
        window.Chargebee.registerAgain();
        // this.setState({ chargebeeReady: true });
    };
    el.setAttribute('data-cb-site', 'derp-test');
    el.setAttribute('src', 'https://js.chargebee.com/v2/chargebee.js');
    document.body.appendChild(el);
}

render() {
    // [...]
    <a
        href="javascript:void(0)"
        data-cb-type="checkout"
        data-cb-plan-id="asdf-test"
    >
        Subscribe
    </a>
    // [...]
}

when clicking subscribe I get an error:

Uncaught TypeError: Cannot read property 'getCart' of null
    at t.a (event-binding.ts:24)
    at Function.value (chargebee.ts:46)
    at HTMLScriptElement.el.onload (Subscribe.js:23)

Solution

  • Chargebee instance will be created when DOMContentLoaded event is triggered.Since, you are loading it asynchronously, instance is not getting created. So you can create the instance using Chargebee.init().

    componentDidMount() {
        const el = document.createElement('script');
        el.onload = () => {
          window.Chargebee.init({
            "site": "derp-test"
          });
          window.Chargebee.registerAgain();
          // this.setState({ chargebeeReady: true });
        };
        el.setAttribute('src', 'https://js.chargebee.com/v2/chargebee.js');
        document.body.appendChild(el);
    }