Firebase SMS Code Expiration on the Same Device-OTP React Native
Firebase sends an OTP verification code on devices after integrating their SDK. Most of the devices are smart enough so we use auto verification and things working smoothly. On the contrary, most of the developers facing an issue that they send OTP code on the same devices but firebase appears a message :
The sms code has expired. Please re-send the verification code to try again
Apparently, the solution comes in our mind that using onAuthStateChanged
method.
componentDidMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// if user data exist
}
});
}
Surprisingly, when you consolidate it shows the previous user instance still present while you authenticate with a new user. The mystery behind that is whenever you call authenticate method. It creates a user on Firebase. Like below:
It means the user is still login. So, here we need to clear the user session in order to prevent SMS code expiration. Therefore, firebase provides a method called auth().signOut().
componentDidMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// if user data exist
//clear previous user session
this.logOutFirebase();
}
});
}
logOutFirebase = () => {
firebase.auth().signOut();
}
Hope it's helpful.