Passing arguments through the global leak pattern

In this notebook, I’m trying to load the stripe module and use it to create links. How can I pass my API key as an argument and use this function?

Your first example was on the right track, but you need to be aware that require() works asynchronously. That means that the value returned by require() is a promise that needs to be awaited/resolved before you can access the Stripe function. Note also that the Stripe documentation emphasizes that the library should always be included from js.stripe.com.

Here are three approaches that essentially do the same:

  1. Let Observable resolve the promise for you:
    Stripe = require('https://js.stripe.com/v3').catch(() => window.Stripe)
    
    stripe = Stripe(key)
    
  2. In a single cell, calling promise.then():
    stripe = require('https://js.stripe.com/v3')
      .catch(() => window.Stripe)
      .then(Stripe => Stripe(key))
    
  3. In a single cell, using await:
    stripe = (
      await require('https://js.stripe.com/v3').catch(() => window.Stripe)
    )(key)
    
2 Likes

Amazing! Thanks a lot for your detailed explanation!

1 Like

I made a minor mistake here. The example above can of course be shortened to:

stripe = require('https://js.stripe.com/v3').catch(() => window.Stripe(key))

I left my original comment unchanged to keep the example of using .then().

2 Likes

I have a working Stripe notebook here, maybe it’s useful to see a working one.

2 Likes