nixn
nixn

Reputation: 1478

React-Native: Firebase Query for parent values

I am completely new to react native and JavaScript. I am trying to search the database for an entered number, which is an child of the users node. If the query found the entered number I want to know if the number is verified. I see all values when I debug that belongs to the user, but I cannot access it.

How do I get the userID value of from my point?

 getUserByPhoneNumber = phoneNumber => {
var ref = firebase.database().ref("/Users");
var query = ref.orderByChild("phone").equalTo("phoneNumber");
query.once("value", function(snapshot) {
  // User found
  if (snapshot.val()) {
    // undefined
    console.log(snapshot.val().phoneVerified);

    // output = "Users"
    console.log(snapshot.key)
  }
});

};

Firebase Datastructure is like this:

/Users
    /uid
        /phone
        /phoneVerified

Upvotes: 0

Views: 751

Answers (2)

nixn
nixn

Reputation: 1478

I solved this by itarating through the snapshot.val()

  getUserByPhoneNumber = phoneNumber => {
var ref = firebase.database().ref("/Users");
var query = ref.orderByChild("phone").equalTo(phoneNumber);
query.once("value", function(snapshot) {
  // User found
  if (snapshot.val()) {
    // Whole user Node is returned - so foreach
    snapshot.forEach(function(childSnapshot) {
      var userID = childSnapshot.key;
      var userData = childSnapshot.val();
      if (userData.phoneVerified) {
        // User is known and Verified -> enter password
      } else {
        // User is known but not Verified -> send Verification
      }
    });
  } else {
    // User NOT found -> register
  }
});

};

Upvotes: 1

Adam Kipnis
Adam Kipnis

Reputation: 10971

I'm assuming your FB structure is

/Users
  /phone
    /phoneNumber
    /phoneVerfied

Function:

getUserByPhoneNumber = phoneNumber => {
  var ref = firebase.database().ref("/Users");
  var query = ref.orderByChild("phone/phoneNumber").equalTo(phoneNumber);
  query.once("value", function(snapshot) {
    const record = metadata.val();

    if (record) {
      const uids = Object.keys(record);

      // Modify this if you can have multiple records per phone number
      if (uids && uids.length > 0 && record[uids[0]].phone.phoneVerified) {
        // Do something with uid
      }
    }
  });
};

Upvotes: 1

Related Questions