npm create vite@latest
npm i firebase
my-app
|
|──────src
| |
| └──────App.jsx
| └──────phone.jsx
|
└──────firebaseConfig.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: "Get Your Key from firebase",
authDomain: "Get Your Key from firebase",
projectId: "Get Your Key from firebase",
storageBucket: "Get Your Key from firebase",
messagingSenderId: "Get Your Key from firebase",
appId: "Get Your Key from firebase",
measurementId: "Get Your Key from firebase",
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
export { auth };
//phone.jsx
import React, { useState } from "react";
import { RecaptchaVerifier, signInWithPhoneNumber } from "firebase/auth";
import { auth } from "../firebaseConfig";
function Phone() {
const [phone, setPhone] = useState("");
const [confirmation, setConfirmation] = useState(null);
const [otp, setOtp] = useState("");
const [otpSent, setOtpSent] = useState(false);
const [isSendingOtp, setIsSendingOtp] = useState(false);
const sendOtp = async () => {
try {
setIsSendingOtp(true);
const recaptcha = new RecaptchaVerifier(auth, "recaptcha", {
size: "invisible",
});
const confirmationResult = await signInWithPhoneNumber(
auth,
phone,
recaptcha
);
setConfirmation(confirmationResult);
setOtpSent(true);
} catch (err) {
console.error(err);
} finally {
setIsSendingOtp(false);
}
};
const verifyOtp = async () => {
try {
const data = await confirmation.confirm(otp);
console.log(data);
saveUserDetails(phone);
} catch (err) {
console.error(err);
}
};
const saveUserDetails = async (phone) => {
try {
console.log("User is Logged in Save the Details in Backend", phone);
} catch (error) {
console.log("Failed to Login user:", error.message);
}
};
return (
<div>
<h2>Phone Verification</h2>
{!otpSent ? (
<>
<input
onChange={(e) => setPhone(e.target.value)}
placeholder="Phone"
/>
<div>
<button onClick={sendOtp} disabled={isSendingOtp}>
{isSendingOtp ? "Sending OTP..." : "Send OTP"}
</button>
</div>
<div>
<div id="recaptcha"></div>
</div>
</>
) : (
<>
<div>
<div>
<input
type="text"
onChange={(e) => setOtp(e.target.value)}
placeholder="OTP"
/>
<button onClick={verifyOtp}>Verify OTP</button>
</div>
</div>
</>
)}
</div>
);
}
export default Phone;
-- Use +918888888888 this format to change this to 8888888888 change the code to Add +91 in sendOtp function --