Skip to content

Instantly share code, notes, and snippets.

@cloud-walker
Created July 30, 2019 10:23
Show Gist options
  • Save cloud-walker/055dfb961dbda76e4ccee3bd1e3d352f to your computer and use it in GitHub Desktop.
Save cloud-walker/055dfb961dbda76e4ccee3bd1e3d352f to your computer and use it in GitHub Desktop.
useStripe React hook
import React from 'react'
let cache = []
const isCached = src => cache.includes(src)
export const useScript = src => {
const [state, setState] = React.useState({
isLoaded: isCached(src),
hasError: false,
})
React.useEffect(() => {
if (!src || isCached(src)) {
return
}
cache.push(src)
const script = document.createElement('script')
script.src = src
script.async = true
const onScriptLoad = () => {
setState(s => ({...s, isLoaded: true, hasError: false}))
}
const onScriptError = () => {
const index = cache.indexOf(src)
if (index >= 0) {
cache.splice(index, 1)
}
script.remove()
setState(s => ({...s, hasError: true, isLoaded: true}))
}
script.addEventListener('load', onScriptLoad)
script.addEventListener('error', onScriptError)
document.body.appendChild(script)
return () => {
script.removeEventListener('load', onScriptLoad)
script.removeEventListener('error', onScriptError)
}
}, [src])
return state
}
import React from 'react'
import {useScript} from './useScript'
let cache = {}
export const useStripe = ({locale}) => {
const {isLoaded, error} = useScript('https://js.stripe.com/v3/')
const [stripe, setStripe] = React.useState(cache[locale])
React.useEffect(() => {
if (isLoaded && !error && !cache[locale]) {
cache[locale] = window.Stripe(process.env.STRIPE_KEY, {locale})
setStripe(cache[locale])
}
}, [isLoaded, error, locale])
return {
stripe,
error,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment