Reputation: 23
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
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.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
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 />
}
Upvotes: 1