问题
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