1

I'm new to ReactJs. I'm trying to create a firebase app using it. So in componentWillMount I'm checking if the user is logined or not and setting the state boolean value according to that

  componentWillMount() {
    var config = {...};
    Firebase.initializeApp(config)

    Firebase.auth().onAuthStateChanged(function(user){
      if(user){
        console.log("User logined");
        this.setState({
          isLogined : true
        })
      }else{
        console.log("User isn't logined");
        this.setState({
          isLogined : false
        })
      }
    })

  }

But it's showing setState() is not a function.

index.js:2178 TypeError: this.setState is not a function
    at Object.next (App.js:31)
    at index.cjs.js:1353
    at index.cjs.js:1457

Need Help :(

Bucky
  • 1,116
  • 2
  • 18
  • 34

2 Answers2

3

Few things:

1) You'll want to move this code to componentDidMount. componentWillMount is deprecated. Here's some more info as to why you should prefer componentDidMount

2) Change your onAuthStateChanged callback to be an arrow function.

componentDidMount() {
var config = {...};
Firebase.initializeApp(config)

Firebase.auth().onAuthStateChanged((user) => {
  if(user){
    console.log("User logined");
    this.setState({
      isLogined : true
    })
  }else{
    console.log("User isn't logined");
    this.setState({
      isLogined : false
    })
  }
})

}
AnilRedshift
  • 7,937
  • 7
  • 35
  • 59
2

The problem comes from:

Firebase.auth().onAuthStateChanged(function(user){

this is not refferring to the react component. Instead, try:

Firebase.auth().onAuthStateChanged((user) => {
bthe0
  • 1,354
  • 2
  • 13
  • 25