Haris Hamzić
Haris Hamzić

Reputation: 23

Problem with Firebase Auth while refrashing a page

I need your ideasssssssss.

renderIt = () => {
    if(!this.state.user){
      return <Login />
    }else {
      return <Home />
    }
  }

here I check is the user is logged in, if he is not logged in <Login /> is displayed, when he logs itself in, then <Home /> is displayed.

Problem is, when I go log out, and refresh, I see <Home/> page for a fraction of a second even if I am not logged in.

componentDidMount = () => {
      this.authListener();
  }

 authListener = () => {
    firebase
      .auth()
      .onAuthStateChanged((user) => user ? this.setState({user}) : this.setState({user: null}))
  }

Upvotes: 1

Views: 153

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

The problem is in your initial state, which is:

class App extends Component {
  state = {
    user: {}
  }
  ...

Since you then check for this.state.user in the rendering code, you end up comparing (!{}) which is false.

I highly recommend keeping this code as simple as possible, following these rules:

  • this.state.user represents the current user object.
  • if there is no current user, this.state.user is null.

In code:

class App extends Component {
  state = {
    user: null
  }

  componentDidMount = () => {
      this.authListener();
  }

  authListener = () => {
    firebase
      .auth()
      .onAuthStateChanged((user) => this.setState({user}));
  }
  ...

Also see the updated working code at: https://stackblitz.com/edit/react-1bv4bb?file=src/App.js

Upvotes: 1

Besufkad Menji
Besufkad Menji

Reputation: 1588

it's because !this.state.user true initially and until firebase auth finishes its work it will show you <Home/>.

The solution is to use a loading (some spinner animation) component initially until the firebase auth finished

if(this.state.user===null){
//create Loading component first before using it here
  return <Loading />
}else if(!this.state.user){
  return <Login />
}else {
  return <Home />
}
  • This might not be a better way to handle user authentication, it's just to answer your question

Upvotes: 1

Related Questions