Tahtoh
Tahtoh

Reputation: 57

Stripe not initialized

i decided to use nextjs with stripe and did it like this, but i get the error Error: Please pass a valid Stripe object to StripeProvider. You can obtain a Stripe object by calling 'Stripe(...)' with your publishable key. i am passing a stripe object but weirdly enough it doesnt go through and even when trying to console.log in next.js its not showing in console. So what am i doing wrong? Thanks

function MyApp({ Component, pageProps }) {
  const [stripe, setStripe] = useState({ stripe: null });
  useEffect(() => {
    console.log("djdsjdjsd");
    if (window.Stripe) {
      setStripe({ stripe: window.Stripe('pk_test') });
    } else {
      document.querySelector('#stripe-js').addEventListener('load', () => {
        // Create Stripe instance once Stripe.js loads
        setStripe({ stripe: window.Stripe('pk_test') });
      });
    }
  }, []);
  return (
    <>
      <Head>
        <title>My page title</title>
        <meta property="og:title" content="My page title" key="title" />
        <script async src="https://js.stripe.com/v3/"></script>
      </Head>
      <StripeProvider stripe={stripe}>
        <Component {...pageProps} />
      </StripeProvider>
    </>
  )
}

Upvotes: 0

Views: 1718

Answers (1)

Nolan H
Nolan H

Reputation: 7439

Instead of trying to build your component around Stripe.js loading like this, you should use the loadStripe helper from @stripe/stripe-js with the Elements provider from @stripe/react-stripe-js. This will handle loading Stripe.js for you asynchronously along with the initialization.

Docs

Example:

import {Elements} from '@stripe/react-stripe-js';
import {loadStripe} from '@stripe/stripe-js';

const stripePromise = loadStripe('pk_test_123');

const App = () => {
  return (
    <Elements stripe={stripePromise}>
      <PaymentComponentWithCardElementEtc />
    </Elements>
  );
};

Upvotes: 2

Related Questions