Uncaught TypeError: Cannot read property 'get' of undefined error

10,330

query.first is an asynchronous function. To use the values it returns, you have to do it in the success: callback function. So pass a callbak to getUsername that performs the login.

function getUsername(email, callback) {
  var query = new Parse.Query(Parse.User);
  query.equalTo('email', email);
  query.first({
    success: function(object) {
      if (object) {
        console.log(object.get("username"));
        callback(object.get("username"));
      } else {
        console.log("email not found");
      }
    },
    error: function(user, error) {
      console.log("no email");
    }
  });
}

function signIn(usernameOrEmail, password) {

  //if not email sign in with username
  if (usernameOrEmail.indexOf("@") == -1) {
    Parse.User.logIn(usernameOrEmail, password, {
      success: function(user) {
        console.log("Logged in!");
      },
      error: function(user, error) {
        alert("Error: " + error.code + " " + error.message);
      }
    });
  }
  //query for username from email and signin
  else {
    getUsername(usernameOrEmail, function(username) {
        signIn(username, password);
    });
  }
}
Share:
10,330
Aaron
Author by

Aaron

Updated on July 21, 2022

Comments

  • Aaron
    Aaron almost 2 years

    I am trying to use either the email or username of the User class to login. However, when I query for the email and try to do

    object.get("username") 
    

    I get the error message above. Strangely, when I test the helper function getUsername in the debugger it works fine

    function getUsername(email) {
      var query = new Parse.Query(Parse.User);
      query.equalTo('email', email);
      query.first({
        success: function(object) {
          console.log(object.get("username"));
          return object.get("username");
        },
        error: function(user, error) {
          console.log("no email");
        }
      });
    }
    
    
    function signIn(usernameOrEmail, password) {
    
      //if not email sign in with username
      if (usernameOrEmail.indexOf("@") == -1) {
        Parse.User.logIn(usernameOrEmail, password, {
          success: function(user) {
            console.log("Logged in!");
          },
          error: function(user, error) {
            alert("Error: " + error.code + " " + error.message);
          }
        });
      }
      //query for username from email and signin
      else {
        var username = getUsername(usernameOrEmail);
        Parse.User.logIn(username, password, {
          success: function(user) {
            console.log("Logged in!");
          },
          error: function(user, error) {
            alert("Error: " + error.code + " " + error.message);
          }
        });
      }
    }