0

I'm trying to check if a user is logged in or not on my React webpage using Firebase, however I keep getting an error TypeError: Cannot read property 'onAuthStateChanged' of undefined, the line of code it links to is as followed:

Login.js:

authListener() {
Fire.auth.onAuthStateChanged((user) => {
  if (user) {
    this.setState({ user })
  } else {
    this.setState({ user: null })
  }
})}

Fire.js:

import firebase from 'firebase'

const config = {
    apiKey: "xxx",
    authDomain: "xxx",
    databaseURL: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx",
    appId: "xxx"
};
const Fire = firebase.initializeApp(config);
export default Fire;

** solved it, above is what my Fire.js and Login.js look like for those coming and having the same problem **

KENdi
  • 7,576
  • 2
  • 16
  • 31
aurelio
  • 57
  • 1
  • 9

1 Answers1

3

You need to include firebase package

import firebase from "firebase";

and then use auth() function of firebase

authListener() {
firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    this.setState({ user })
  } else {
    this.setState({ user: null })
  }
})}

if you are importing firebase from another file then configure it like this

import firebase from 'firebase/app';
import 'firebase/auth';
export const init = () => {
    let config = {
        apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        authDomain: 'xxxxxxxxxxxxx'
    };
    firebase.initializeApp(config);
};

export const firebaseAuth = firebase.auth;
Gopal
  • 455
  • 5
  • 14
  • I can't `import firebase from "firebase";` in another file called `Fire.js` and then import `Fire.js` and use `Fire.auth().onAuthStateChanged()`? – aurelio May 30 '19 at 06:56