Skip to content

Instantly share code, notes, and snippets.

@ozluy
Last active September 25, 2019 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozluy/207b4bf832eb601970d84136ad3fb819 to your computer and use it in GitHub Desktop.
Save ozluy/207b4bf832eb601970d84136ad3fb819 to your computer and use it in GitHub Desktop.
Solution for loading Stripe.js and Stripe Elements
import React, { useState, useEffect } from 'react'
const StripeScriptLoader = ({
children,
uniqueId,
script,
loader = 'Loading...',
}) => {
const [stripeLoaded, setStripeLoaded] = useState({})
useEffect(() => {
const loadScript = (src, uniqueId) =>
new Promise((resolve, reject) => {
const scriptElement = document.getElementById(uniqueId)
if (!scriptElement) {
const script = document.createElement('script')
script.src = src
script.id = uniqueId
const handleLoadScriptSuccess = () => resolve({ successful: true })
const handleLoadScriptFail = event => reject({ error: event })
script.addEventListener('load', handleLoadScriptSuccess, {
once: true,
})
script.addEventListener('error', handleLoadScriptFail, { once: true })
document.head.appendChild(script)
} else {
resolve({ successful: true })
}
})
const fetchData = async () => {
const result = await loadScript(script, uniqueId)
setStripeLoaded(result)
}
fetchData()
}, []) // eslint-disable-line react-hooks/exhaustive-deps
return stripeLoaded.successful ? children : loader
}
export default StripeScriptLoader
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment