I'm using React Router v5.2.0 and implementing public / private routes with async authentication. Essentially the workflow is: PublicRoute for login, PrivateRoute for dashboard and a PublicRoute for /landing (so if a user is logged in, but they aren't subscribed to a service they will be redirected to a landing page).
All of my routes work except for '/landing' The app will redirect to /landing succesfully, but the Landing component doesn't show / mount. (The console.log will not trigger either)
I am using redux and I've tried adding withRouter but receive the same error. If I remove the public or private route component and use a regular Route, the component will show.
App.js
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/" component={Dashboard} />
<PublicRoute exact restricted={true} path="/landing" component={Landing} />
<PublicRoute exact restricted={false} path="/login" component={Login} />
</Switch>
</BrowserRouter>
PublicRoute:
class PublicRoute extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
isAuthenticated: false,
isSubscribed: false
};
}
async componentDidMount() {
console.log("loading");
const isLoginCheck = await isLogin();
const isSubscribedCheck = await isSubscribed();
this.setState({
loading: false,
isAuthenticated: isLoginCheck || false,
isSubscribed: isSubscribedCheck || false
})
}
render() {
const { component: Component, restricted, ...rest } = this.props;
return (
<Route
{...rest}
render={props => (
//If a user is authenticated, subscribed and the route is restricted, redirect to dashboard
this.state.isAuthenticated && this.state.isSubscribed && restricted ? (
<Redirect to="/" />
) : this.state.loading ? (
//If loading, show a loading component (placeholder currently)
<div>LOADING</div>
) : this.state.isAuthenticated && (!this.state.isSubscribed) ? (
//If the user is authenticated, but not subscribed. redirect to landing
<Redirect to="/landing" />
) :
(
//Else redirect to the component.
<Component {...props} />
))
}
/>
);
}
}
export default PublicRoute;
Landing:
class Landing extends React.Component {
componentDidMount() {
console.log('component mounted');
}
render() {
console.log('Component was called');
return (
<h1>Landing page - not a valid subscriber. </h1>
)
}
}
export default Landing;
Thanks!