wait for loading paypal script in nextjs page

All we need is an easy explanation of the problem, so here it is.

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?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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);
  }

}, []);

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply