Last active
September 25, 2019 12:21
-
-
Save ozluy/207b4bf832eb601970d84136ad3fb819 to your computer and use it in GitHub Desktop.
Solution for loading Stripe.js and Stripe Elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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