I'm using Google's reCAPTCHA v.3 in a React application and I've encountered an issue where window.grecaptcha.enterprise.execute(reCaptchaKey, { action }) returns the same token on the second call even when the action changes. However, on the third call, it returns a new token as expected.
Here's a snippet of my code:
export const useReCaptcha = ({ reCaptchaKey, action, isSubmit }: UseReCaptchaProps): string => {
const [token, setToken] = useState<string>('');
const [scriptLoaded, setScriptLoaded] = useState<boolean>(false);
useEffect(() => {
const script = document.createElement('script');
script.src = `https://www.google.com/recaptcha/enterprise.js?render=${reCaptchaKey}`;
script.onload = () => {
setScriptLoaded(true);
};
script.onerror = () => {
console.error('Failed to load reCAPTCHA script');
setToken(RECAPTCHA_ERROR_MESSAGE);
};
document.head.appendChild(script);
return () => {
document.head.removeChild(script);
};
}, []);
useEffect(() => {
if (isSubmit && scriptLoaded) {
setToken('');
window.grecaptcha.enterprise.ready(async () => {
try {
const reCaptchaToken = await window.grecaptcha.enterprise.execute(reCaptchaKey, { action });
setToken(reCaptchaToken);
} catch (error) {
console.error(error);
setToken(RECAPTCHA_ERROR_MESSAGE);
}
});
}
}, [isSubmit, scriptLoaded, reCaptchaKey, action]);
return token;
};
I've ensured that the action is unique for each call, but I'm still getting the same token on the second call. Is there a workaround for this issue? Any help would be appreciated.
you are setting token in state which is asynchronous, so when you are using a hook's returned value it may return not updated value, which is previous, so you end up with using the same token twice
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With