Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Last active December 8, 2020 14:28
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mrcoles/8c79595f488f0e334e528163feb23293 to your computer and use it in GitHub Desktop.
Save mrcoles/8c79595f488f0e334e528163feb23293 to your computer and use it in GitHub Desktop.
A react provider abstraction for loading the stripe.js file asynchronously to use with Stripe Elements
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { StripeProvider } from 'react-stripe-elements';
export default class AsyncStripeProvider extends Component {
static propTypes = {
apiKey: PropTypes.string.isRequired
};
// constructor
constructor(props) {
super(props);
this.state = {
stripe: null
};
}
// life-cycle
componentDidMount() {
this._mounted = true;
const { apiKey } = this.props;
const stripeJs = document.createElement('script');
stripeJs.src = 'https://js.stripe.com/v3/';
stripeJs.async = true;
stripeJs.onload = () => {
if (this._mounted) {
this.setState({
stripe: window.Stripe(apiKey)
});
}
};
document.body && document.body.appendChild(stripeJs);
}
componentWillUnmount() {
this._mounted = false;
}
// render
render() {
const { stripe } = this.state;
return (
<StripeProvider stripe={stripe}>
<>{this.props.children}</>
</StripeProvider>
);
}
}
@mrcoles
Copy link
Author

mrcoles commented Feb 12, 2019

This is can be used in place of the Stripe Elements StripeProvider component, to asynchronously load the "stripe.js" file. It takes an apiKey as the only prop. Make sure in any direct stripe calls, like stripe.createSource(…) you verify that props.stripe is not null.

import AsyncStripeProvider from './AsyncStripeProvider';

export default () => {
  return (
    <AsyncStripeProvider apiKey={STRIPE_PUBLIC_KEY}>
      <MyApp />
    </AsyncStripeProvider>
  );
}

This is inspired by this Stripe async demo code.

@daviseford
Copy link

Thanks!

@daviseford
Copy link

daviseford commented Sep 26, 2019

This inspired me to write a Hooks version of this component: https://gist.github.com/daviseford/4a0ed622dc47090fe22c1870217d88d6

@mrcoles
Copy link
Author

mrcoles commented Sep 26, 2019

@daviseford awesome! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment