I have the following function that's executed whenever recaptcha should be used. The problem is that the script is not ready or is not yet appended as child when I want to use grecaptcha. Document.createElement("recaptcha_script") is always null when I want to use it. I'm not sure if there is a better way or a solution to my problem. I don't want to use a npm package.
export const RecaptchaAPI = async () => {
const recaptchaScript = async () => {
const script = document.createElement("recaptcha_script");
script.src =`https://www.google.com/recaptcha/api.js?render=${process.env.REACT_APP_RECAPTCHA_SITE_KEY}`;
script.async = true;
document.body.appendChild(script);
script.onload = recaptchaRequest();
}
const recaptchaRequest = () => {
const element = document.getElementById("recaptcha_script");
element.grecaptcha.ready(() => {
element.grecaptcha.execute('reCAPTCHA_site_key').then((token) => {
console.log("worked");
});
});
}
return await recaptchaScript()}