I'm not sure if my answer applies to this question since I used the invisible ReCaptcha. But I had the exact same error message and ended up here to find the answer.
In my case, because of the invisible property the website user didn't prompt the captcha verification by clicking 'I'm not a robot', so it was necessary to programmatically execute the captcha to get the token.
I came up with the following solution.
const Form = () => {
//form answers are saved as templateParams
const [templateParams, setTemplateParams] = useState({
azienda: '',
email: '',
piva: '',
codicefiscale: '',});
//reference to recaptcha
const recaptchaRef = React.useRef<ReCAPTCHA>(null);
//setting the form params on input change
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setTemplateParams({...templateParams, [e.taget.name]: e.target.value});
}
const submitInput = (token) => {} //see declaration below
//executing captcha on formsubmit
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const token = await recaptchaRef.current.executeAsync(); //executeAsync executes the captcha and awaits the result if user input is required.
token && submitInput(token); //when the token is ready, the actual submit function is called
return (
<form onSubmit={handleSubmit}>
<ReCAPTCHA
ref={recaptchaRef}
size="invisible" //removing the 'I'm not a robot' box
sitekey={process.env.PUBLICRECAPTCHAKEY}
<input name='azienda' onChange={handleChange} />
...
</form>
)
}
The form data has been saved in state and the captcha has been executed - meaning that if there is suspicious behaviour, the user is asked to complete the puzzle. Once the token is available, the following function is called:
const submitInput = (token: string | null) => {
const params = {
...templateParams,
'g-recaptcha-response': token
}
emailjs.send(
'your_service_name',
'your_template_name',
params,
'g-recaptcha-response': token
)
.then(() => {
recaptchaRef.current.reset(); // resetting captcha so it has to be completed again before sending a new message
}, err => {
console.error(err)
//and inform the user that submission failed
}
}