0

I am a beginner and trying to use firebase for my react native project authentication. I am able to authenticate user, print the user details and/or catch error if there is any while authenticating. But I am unable to return the value to another function. My project hierarchy: project |->utils/firebaseConnection.js |->Components/Login.js

This is my firebase authentication code:

export function loginUser (email,password) {
  firebase.auth().signInWithEmailAndPassword(email,password)
    .then(user => {
      console.log('user: ', user)
      return user
    })
}

I am able to print user data in the console but I am not able to see the return value in Login component. Below is the code for login component method:

 import * as firebaseAPI from '../utils/firebaseConnection'
    ...
    ...
    loginUser (email,password) {
        console.log('l1: ', firebaseAPI.loginUser(email,password));
      }

but l1 prints "undefined". I even tried firebaseAPI.loginUser(email,password).then(user) , but even this yields undefined error. Please help me out. Thank you. I can give you more info if required.

kumar111
  • 33
  • 2
  • 10

1 Answers1

0

You cannot return something from an asynchronous call. See the link that JJJ provided for a longer explanation, but it basically means you should just return the promise that you get from signInWithEmailAndPassword and put the then() in your calling code:

export function loginUser (email,password) {
  return firebase.auth().signInWithEmailAndPassword(email,password)
}

loginUser (email,password).then(user => {
    console.log('l1: ', user);
  });
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • This worked thank you. I was trying to return from asynchronous firebase.auth() because I want all my code to be done on the utils and only return the required value to login component so that my code looks structured. – kumar111 Jun 25 '18 at 04:25
  • I hope my answer and the one linked explained why returning the value isn't possible. Most modern web APIs work this way, so it's best to get used to this style of coding quickly. – Frank van Puffelen Jun 25 '18 at 14:20