简体   繁体   中英

where to place firebase.auth().onAuthStateChanged in React

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM