Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External js is loading in react component only after refresh

My Component.

import useScript from "./useScript";
function MyComponent(): JSX.Element {
useScript("https://dev-kpaymentgateway.kasikornbank.com/ui/v2/kinlinepayment.min.js", "pkey_test_20184OBD88Yvl6uplpR0kY0ZTpVz46h1Tdqyj");
return (
    <div className={greyContainer}>
        <div className={gridContainer}>

            <p id="error-summary">
                Oops something went wrong, please try again.
            </p>

            <div className="flied">
                <label className="label"> name</label>

                <div id="name"></div>
                <label> Name is invalid.</label>
            </div>

            <div className="flied">
                <label className=" label">Number</label>

                <div id="number"></div>
                <label>Number is invalid.</label>
            </div>

        </div>
        <div style={{textAlign: "right", marginBottom: 10, marginTop: 30}}>
            <form method="POST" action="https://httpbin.org/post">
                <button type="submit" className="pay-button">Pay now</button>
            </form>
        </div>

    </div>
);
}

I load script using react hook. This script is supposed to add some field in component above.

import { useEffect } from "react";

const useScript = (url, dataKey) => {
useEffect(() => {
    const script = document.createElement("script");

    script.src = url;
    script["data-key"] = dataKey;
    script["data-lang"] = "en";
    script["data-write-log"] = true;
    script.async = true;

    document.body.appendChild(script);

    return () => { document.body.removeChild(script);};
    }, [url]);
  };

  export default useScript;

My script is loading but only after refresh the page where I have used the component MyComponent. I am using react-router5 for navigation.

Can anybody explain why it is happening and how to overcome it.

like image 473
Mritunjay Upadhyay Avatar asked Apr 26 '26 02:04

Mritunjay Upadhyay


1 Answers

My best guess is that the kinlinepayment.min.js script was executed just fine. But it registers an event listener for an event that already happened and will not happen again:

document.addEventListener("DOMContentLoaded",e())

You could try to dispatch that event (and all backup events if you need to support old browsers) in your useEffect:

...
document.body.appendChild(script);

document.dispatchEvent(new Event('DOMContentLoaded')))

return ...
like image 84
Aprillion Avatar answered Apr 27 '26 16:04

Aprillion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!