Eric_WVGG
Eric_WVGG

Reputation: 2947

Event listener for window.stripe

I have a Stripe integration in a React web front-end. My payment component attempts to run…

componentDidLoad() {
  if ( window.hasOwnProperty('Stripe') ) {
    this.setState({stripe: window.stripe(config.stripeKey)})
  }
}

This sporadically fails as sometimes the React app will boot and get the component loaded before window.stripe exists. I’m currently resolving this with…

componentDidLoad() {
  this.watchStripe = setInterval( () => {
    if (!props.stripe && isBrowser && window.Stripe) {
      this.setState({stripe: window.stripe(config.stripeKey)})
      clearInterval(this.watchStripe)
    }
  }, 100)
}

Is there a more elegant solution to this, something that doesn't require an interval timer?

Upvotes: 0

Views: 642

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

If you read the Advanced integrations section they suggest doing

componentDidMount() {
    if (window.Stripe) {
      this.setState({stripe: window.Stripe('pk_test_12345')});
    } else {
      document.querySelector('#stripe-js').addEventListener('load', () => {
        // Create Stripe instance once Stripe.js loads
        this.setState({stripe: window.Stripe('pk_test_12345')});
      });
    }
  }

This adds an event listener for the load event on the script element that loads Stripe and sets the state when it is available (so no continuous polling with setInterval,setTimeout is needed)

Upvotes: 1

Related Questions