I was trying to add firebase phone otp verification on a project but getting frustrated by the message of recatcha has already been rendered on this element ,on a first try the otp sends successfully to the mobile number and goes to verified page but whenever I try to navigate to the otp send page again using back arrow key of the browser gives that recaptcha rendered error I thought on return If I clear the recaptchaVerifier It will be fixed but it did not solve the problem
Code:
typeexport default function testPage() {
const app = initializeApp(firebaseConfig);
const router = useRouter();
const inputRef = useRef(null);
const checkboxRef = useRef(null);
useEffect(() => {
if(!window.recaptchaVerifier){
const auth = getAuth(app);
try {
// Check if reCAPTCHA has already been rendered
window.recaptchaVerifier = new RecaptchaVerifier(auth, "sendCode", {
size: "invisible",
callback: async function (recaptchaToken) {
// reCAPTCHA solved, send recaptchaToken and phone number to backend.
const phoneNumber = inputRef.current.value;
console.log(recaptchaToken);
try {
await signInWithPhoneNumber(
auth,
phoneNumber,
window.recaptchaVerifier
);
console.log("OTP sent successfully");
router.push("/verified");
} catch (error) {
console.log("Error signing in:", error);
}
},
});
// Render the reCAPTCHAVerifier.
window.recaptchaVerifier.render().then(function (widgetId) {
window.recaptchaWidgetId = widgetId;
});
} catch (error) {
console.error("Error creating/re-rendering reCAPTCHA verifier:", error);
}
return () => {
// Clear the reCAPTCHAVerifier only if it has been rendered
if (window.recaptchaWidgetId) {
console.log("Clearing reCAPTCHA verifier");
try {
window.recaptchaVerifier.clear();
window.recaptchaVerifier = null; // Reset the verifier
window.recaptchaWidgetId = null; // Reset the widgetId
} catch (error) {
console.error("Error clearing reCAPTCHA verifier:", error);
}
}
};
}
}, []); // Add 'app' to the dependency array if it's not declared in the code you provided
return (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100vh",
width: "100vw",
color: "black",
flexDirection: "column",
}}
>
<div style={{ display: "flex" }}>
<input id="isSignup" ref={checkboxRef} type="checkbox" />
<label for="isSignup">isSignup</label>
</div>
<div style={{ display: "flex" }}>
<input ref={inputRef} />
<button id="sendCode"> send otp </button>
</div>
</div>
);
}
I have tried to search on the google about the solution but did not get fixable solution