5

Stripe has react-stripe-elements, which provides injectStripe HOC. We're in 2019 and HOCs are not cool anymore. Stripe doesn't appear to be in a hurry, i assume it's because they want to support older versions of React, so are looking at lowest common denominator solutions only.

I'm looking for a way to get stripe via a hook (instead of a prop provided by injectStripe).

Usage would look like this const stripe = useStripe() so that later I can use stripe.handleCardSetup and other API methods

import { CardElement } from 'react-stripe-elements'

const CardForm = ({secret}) => {
  const stripe = useStripe()

  const handleSubmit = async () => {
    const { setupIntent, error } = await stripe.handleCardSetup(secret)
    // ...
  }

  return (
    <>
      <CardElement />
      <button onClick={handleSubmit} />
    </>
  )
}

how would you define useStripe hook from existing APIs and components? stripe should be the same as what you'd get if you used injectStripe hook

Related issue on GH: API Review: Hooks & Beyond

1
  • Looking to the open repo, even if they want to, this will take a while since they implemented everything as a HOC, they will eventually need to provide the same logic in modular bases besides what they have as a Class Based component.
    – Sultan H.
    Jul 30, 2019 at 6:06

2 Answers 2

8

After a bunch of trial and error, i ended up with this, which is quite simple. Here it is for stripe peeps to adopt and for others who need useStripe hook

// StripeHookProvider.jsx

import React, { useContext, createContext } from 'react'
import { injectStripe } from 'react-stripe-elements'

const Context = createContext()

export const useStripe = () => useContext(Context)

const HookProvider = ({ children, stripe }) => {
  return <Context.Provider value={stripe}>{children}</Context.Provider>
}

export default injectStripe(HookProvider)

Import and add StripeHookProvider to your component hierarchy like this. NOTE: because it relies on injectStripe, it must be a child of <Elements>

    <StripeProvider {...{ stripe }}>
      <Elements>
        <StripeHookProvider>
          <MyForm />
        </StripeHookProvider>
      </Elements>
    </StripeProvider>

then inside MyForm you use it like this

// MyForm.jsx
import { useStripe } from './StripeHookProvider'

const MyForm = () => {
  const stripe = useStripe()

  const handleSubmit = () => {
    const { setupIntent, error } = await stripe.handleCardSetup(secret ... // and so on
  }
}

This way you only need to do injectStripe in one place and it's tucked away neatly out of sight. As you can see from this code, it's not rocket science and should be no problem for stripe peeps to add to their code, hopefully eliminating <StripeHookProvider> altogether since they have a reference to stripe object somewhere in context.

I tried a bunch of approaches and this is the only one that worked. I didn't dig through stripe's JS code to see what happens, but stripe you get from injectStripe is the only thing you can use. The one you setup via window.Stripe(apiKey) is not the same and it won't work as it doesn't observe <Elements> properly so it doesn't know the state of the form.

Perhaps, the reason injectStripe has to be used on children of <Elements> is the same reason Stripe crew is taking a while to build this hook.

1
  • 2
    its a shame I cant vote up a hundred times - worked first time! Oct 3, 2019 at 21:38
2

I've done it myself, and I've prepared a gist for you :)

The useStripe hook uses a useScript hook that its responsible to load async scripts like the stripe one..

Here is the gist:useScript.js

I've simplified it, you may not need the locale either.

Here is the useScript:

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
}

Here is the useStripe hook:

import React from 'react'

import {useScript} from './useScript'

let cache = {}

export const useStripe = ({locale, stripeKey}) => {
  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(stripeKey, {locale})
      setStripe(cache[locale])
    }
  }, [isLoaded, error, locale])

  return {
    stripe,
    error,
  }
}

This is just the hook, but if you need the context API's you can move the useStripe code inside the Provider!

3
  • linking to Gists is not good form for StackOverflow. either way, your approach doesn't quite work. I tried something like that in my explorations and found that if you simply try to store what you get from window.Stripe(apiKey) in context it doesn't work with <Elements> because it doesn't know that element has value
    – Andrei R
    Jul 31, 2019 at 7:28
  • Your gist has nice an interesting approach to loading stripe in a hook-y way, which can help hide a bit of setup code.
    – Andrei R
    Jul 31, 2019 at 7:29
  • Sorry, it was a while since the last time I've used StackOverflow, I will update the response :) And my solution was not meant to be used with the official react package, its just a hook the returns the stripe instance! With hooks its not that hard to redo the react elements thing anyway Jul 31, 2019 at 8:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.