Firebase onAuthStateChanged error with React

北慕城南 提交于 2021-01-29 14:24:41

问题


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:


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;


来源:https://stackoverflow.com/questions/56372981/firebase-onauthstatechanged-error-with-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!