Home > front end >  How to match phone number with the phone number present in firebase real-time database (react-native
How to match phone number with the phone number present in firebase real-time database (react-native

Time:08-11

I want to create a login form using firebase authentication in which the only user who is register in our database can login. Here I want to take user phone number from login form and match it with firebase real-time database, if the is present in database then the OTP will send to that phone number otherwise they get a popup message you are not register please register then login.

My database structure is like this,

{
 914587354986
{
name:abc
address:kolkata
email:[email protected]
}
}

I have tried this way, you can see my code

function getData(phoneNumber){
  var ref=firebase.app().database('https://phone-otp-verify-17c40-default-rtdb.firebaseio.com/').ref("/user/")
  ref.once('value')
  .then(snapshot => {
    console.log('User data: ', snapshot.val());
    })
  
    if((snapshot.val()) == phoneNumber){
      signInWithPhoneNumber(phoneNumber);
    }else{
      alert('number is not register ');
    }
 }
  
 
   const signInWithPhoneNumber=async()=> {
   try{
    const confirmation = await auth().signInWithPhoneNumber(phoneNumber)
    setConfirm(confirmation);
      alert('Otp send sucessfully');
      console.log('Otp send sucessfully');
    }catch(error){
      alert('Not register');
      console.log(' Not register');

    }
    };

   const confirmCode = async()=> {
    try {
      await confirm.confirm(code);
       alert('sucessfull ');
       console.log('sucessfull');
       navigation.navigate('Home');
    } catch (error) {
       alert('Invalid code.');
      console.log('Invalid code.');
      
    }
  };

I was getting error :ReferenceError: Can't find variable: snapshot image of the error I was getting error image

CodePudding user response:

You are accessing snapshot outside then callback. Move it inside.

function getData(phoneNumber) {
  var ref = firebase.app().database('https://phone-otp-verify-17c40-default-rtdb.firebaseio.com/').ref("/user/");

  ref.once('value')
  .then(snapshot => {
    console.log('User data: ', snapshot.val());
  
    if (snapshot.val() == phoneNumber) {
      signInWithPhoneNumber(phoneNumber);
    } else {
      alert('number is not register ');
    }
  });
}

CodePudding user response:

Just a minor mistake

You are using snapshot.val() outside from scope.

The function should look like this

function getData(phoneNumber) {
    var ref = firebase.app().database('https://phone-otp-verify-17c40-default-rtdb.firebaseio.com/').ref("/user/")
    ref.once('value')
        .then(snapshot => {
            console.log('User data: ', snapshot.val());

            if ((snapshot.val()) == phoneNumber) {
                signInWithPhoneNumber(phoneNumber);
            } else {
                alert('number is not register ');
            }
        })
    }

  • Related