Taio
Taio

Reputation: 3734

wait for loading paypal script in nextjs page

I have this code that is supposed to render the PayPal buttons.

    <Head>
      <script src="https://www.paypal.com/sdk/js?client-id=KEY"></script>
    </Head>

I load the PayPal buttons in the componentDidMount method

componentDidMount() {
    paypal
.Buttons({
  createOrder: (data, actions)=> {
    return actions.order.create({
      purchase_units: [{
          amount: {
            currency_code: "USD",
            value: amount,
          },
        }],
    });
  },
  onCancel: function(data){
    //console.log(data)

  },
  onError: function(err){
    console.log(err)
  }
})
.render("#paypal");
 }




<div id="paypal" className=""></div>

on the first page load, the page throws an error that PayPal is not defined I am guessing because the script is not loaded fully when the componentDidMount method is called. How can I wait until the script is loaded for the buttons to be rendered properly?

Upvotes: 3

Views: 2094

Answers (1)

Yilmaz
Yilmaz

Reputation: 49571

const addPayPalScript = () => {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = `https://www.paypal.com/sdk/js?client-id=${process.env.PAYPAL_CLIENT_ID}`;
    // script.setAttribute("data-namespace", "paypal_sdk");

    script.async = true;
    script.onload = () => {
      setSdkReady(true);
    };
    document.body.appendChild(script);
  };

script.onload will flag that it is ready. Track it in useState

   const [sdkReady, setSdkReady] = useState(false);

then call addPayPalScript inside useEffect or componentDidMount. I use useEffect

useEffect(() => {
dispatch(orderDetailRequestStart(paramsId));

  if (!window.paypal) {
    addPayPalScript();
  } else {
    // flags that it is ready
    setSdkReady(true);
  }

}, []);

Upvotes: 4

Related Questions