I'm facing an issue in my app, when the user is authenticated and he types in the desired link address manually, which he has access to, the page redirects him to the home page. This doesn't happen when simply clicking on the links.
Here is the code:
const asyncCheckout = asyncComponent(() => {
return import('./containers/Checkout/Checkout');
});
const asyncOrders = asyncComponent(() => {
return import('./containers/Orders/Orders');
});
const asyncAuth = asyncComponent(() => {
return import('./containers/Auth/Auth');
});
class App extends Component {
componentDidMount() {
this.props.onTryAutoSignup();
}
render() {
let routes = (
<Switch>
<Route path="/auth" component={asyncAuth} />
<Route path="/" exact component={BurgerBuilder} />
<Redirect to="/" />
</Switch>
);
console.log('Is authenticated: ' + this.props.isAuthenticated);
console.log(routes.props.children);
if (this.props.isAuthenticated) {
routes = (
<Switch>
<Route path="/checkout" component={asyncCheckout} />
<Route path="/orders" component={asyncOrders} />
<Route path="/logout" component={Logout} />
<Route path="/auth" component={asyncAuth} />
<Route path="/" exact component={BurgerBuilder} />
<Redirect to="/" />
</Switch>
);
}
console.log('Is authenticated: ' + this.props.isAuthenticated);
console.log(routes.props.children);
return (
<div>
<Layout>
{routes}
</Layout>
</div>
);
}
}
const mapStateToProps = state => {
return {
isAuthenticated: state.auth.token !== null
};
};
const mapDispatchToProps = dispatch => {
return {
onTryAutoSignup: () => dispatch(actions.authCheckState())
};
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
Here is what the console.logs show, when manually typing in the links:
Is authenticated: false
App.js:38 Array(3)
App.js:55 Is authenticated: false
App.js:56 Array(3)
App.js:37 Is authenticated: true
App.js:38 Array(3)
App.js:55 Is authenticated: true
App.js:56 Array(6)
It seems like it does this, because when manually typing in addresses, the page has to reload, and that's why user will always be unauthenticated at first.
I tried messing with the props that the react-router giveds us in order to somehow still successfully redirect the user to the correct page, but the this.props.match.url
and this.props.match.path
is always set to "/", even when clicking on links.
So my two questions are:
- How should I handle the redirection, when the user manually types in the desired address, when he is authenticated (token is set in localStorage)?
- How should I fix the react-router situation?