Trying to load in a form from a third party service
They want us to load the script for their service then another script to populate the form with html/data
//load the marketo script if it doesn't exist already
const loadMarketoScript = (callback) => {
const existingScript = document.getElementById('mktoForms');
if (!existingScript) {
const script = document.createElement('script');
s.id = "mktoForms";
s.type = "text/javascript";
s.async = true;
s.src = "//app-ab11.marketo.com/js/forms2/js/forms2.min.js";
document.getElementsByTagName("head")[0].appendChild(script);
script.onload = () => {
if (callback) callback();
};
}
if (existingScript && callback) callback();
};
export default loadMarketoScript;
//page calling the function to load the script
const [loaded, setLoaded] = useState(false);
useEffect(() => {
loadMarketoScript(() => {
setLoaded(true);
});
});
useEffect(() => {
MktoForms2.loadForm("//748-KKO-677.mktoweb.com", "748-KKO-677", 1169);
}, [loaded]);
However MktoForms2 shows as undefined. Unsure what to do here.
It seems the second
useEffecthook doesn't wait for anything to actually be loaded prior to callingMktoForms2.loadForm(....);. TheuseEffecthook is guaranteed to be called on the initial render, and then again anytime a dependency updated.The first
useEffecthook is also missing its dependency array, so anytime the component renders the callback will be called andloadMarketoScriptwill be called. An empty dependency array should be added if you only want to attempt to load the market script when the component mounts.Alternatively you could call
MktoForms2.loadForm(....);in theloadMarketoScriptcallback that is only ever called after the script is loaded.