0
votes

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 **

1
I think it should be Fire.auth().onAuthStateChanged instead of Fire.auth.onAuthStateChangedNiraj Kaushal
I've tried that, it returns TypeError: _Fire__WEBPACK_IMPORTED_MODULE_1__.default.auth is not a functionaurelio
What does Fire hold? From where you imported this? Could you share the code of fire.js file?Niraj Kaushal
I edited my original post to show what is in Fire.jsaurelio

1 Answers

3
votes

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;