The error you're encountering likely stems from the fact that Firebase Authentication methods, such as signInWithPhoneNumber(), are asynchronous, and you're attempting to use them before Firebase has finished initializing.
To fix this issue, you should ensure that Firebase has finished initializing before attempting to use any Firebase Authentication methods. You can achieve this by waiting for the Firebase app initialization to complete before calling getCode().
Here's how you can modify your code to ensure Firebase initialization is complete before calling getCode():
import { initializeApp } from 'firebase/app';
import { getAuth, RecaptchaVerifier } from 'firebase/auth';
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_MEASUREMENT_ID"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
// Wait for Firebase initialization to complete
app.then(() => {
const recaptchaContainer = document.getElementById('recaptcha-container');
const recaptchaVerifier = new RecaptchaVerifier(recaptchaContainer, {
size: 'invisible',
callback: (response) => {
console.log('reCAPTCHA resolved');
},
'expired-callback': () => {
console.log('reCAPTCHA expired');
}
}, auth);
async function getCode(phoneNumber) {
try {
const confirmationResult = await auth.signInWithPhoneNumber(phoneNumber, recaptchaVerifier);
console.log('Code sent:', confirmationResult);
} catch (error) {
console.error('Error during sign-in with phone number:', error);
console.error('Error code:', error.code);
}
}
// Example usage
getCode('+91112223334');
}).catch(error => {
console.error('Firebase initialization error:', error);
});
By waiting for the app promise to resolve, you ensure that Firebase is fully initialized before attempting to use Firebase Authentication methods. This should resolve the error you're encountering.