Reputation: 386
I have a problem, when refresh page, first of all shows <NavigationNonAuth/>
because authUser
the result has not come yet and in a second shows <NavigationAuth/>
What is the best practice to show loading when i am waiting for authUser
const Navigation = () => (
<div>
<AuthUserContext.Consumer>
{authUser => (
authUser ? <NavigationAuth/> : <NavigationNonAuth/>
)
}
</AuthUserContext.Consumer>
</div>
);
const NavigationAuth = () => (
<nav className="navbar bg-white border btn-lg fixed-top justify-content-start p-3">
<Link className="navbar-brand text-dark" to={ROUTES.DASHBOARD}>Dashboard</Link>
<Link className="navbar-brand text-dark" to={ROUTES.SEARCH}>Search</Link>
<Link className="navbar-brand text-dark" to={ROUTES.SETTINGS}>Settings</Link>
<SignOutButton/>
</nav>
);
const NavigationNonAuth = () => (
<nav className="navbar bg-white btn-lg fixed-top justify-content-start p-3">
<Link className="navbar-brand text-dark" to={ROUTES.DASHBOARD}>Landing</Link>
<Link className="navbar-brand text-dark" to={ROUTES.SIGN_IN}>Sign In</Link>
</nav>
);
export default Navigation;
context.js
const AuthUserContext = React.createContext(null);
export default AuthUserContext;
withAuthentication.js
const withAuthentication = Component => {
class WithAuthentication extends React.Component {
constructor(props) {
super(props);
this.state = {
authUser: null,
};
}
componentDidMount() {
this.listener = this.props.firebase.auth.onAuthStateChanged(
authUser => {
authUser
? this.setState({ authUser })
: this.setState({ authUser: null });
},
);
}
componentWillUnmount() {
this.listener();
}
render() {
return (
<AuthUserContext.Provider value={this.state.authUser}>
<Component {...this.props} />
</AuthUserContext.Provider>
);
}
}
return withFirebase(WithAuthentication);
};
export default withAuthentication;
Upvotes: 0
Views: 1463
Reputation: 284
In your render function do something like this:
constructor() {
this.state = { isLoading: true }
}
componentDidMount() {
this.setState({isLoading: false})
}
render() {
return(
this.state.isLoading ? *showLoadingScreen* : *yourPage()*
)
}
Initialize isLoading as true in the constructor and false on componentDidMount
Upvotes: 1