I am trying to call firebase.auth().onAuthStateChanged
in my react component. Firebase is working and the console.log("hi")
is triggered. However, it triggers permanently rather than just on logging in. As a result, I can see a never ending stream of console logs. How can I edit the below to achieve the desired result?
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/storage';
import './App.css';
import React, { Component } from 'react';
const firebaseConfig = {
...
};
firebase.initializeApp(firebaseConfig)
const auth = firebase.auth()
const database = firebase.database()
var database_ref = database.ref()
var storageRef = firebase.storage().ref();
class App extends Component {
state={}
render(){
firebase.auth().onAuthStateChanged((curUser) => {
if(curUser!=null){
console.log("hi")
})
}})
return (<React.Fragment></React.Fragment>);
};
}
export default App;
Thanks in advance
CodePudding user response:
In class components, the spot for this is typically componentDidMount, and tear down the subscription in componentWillUnmount:
class App extends Component {
componentDidMount() {
this.unsubscribe = firebase.auth().onAuthStateChanged((curUser) => {
if(curUser!=null){
console.log("hi")
}
}})
}
componentWillUnmount() {
this.unsubscribe();
}
// ...
}
You may want to set state when the user changes, so the component can rerender and other parts of the code can use the new user.