After reloading the PrivateRoute redirects to /login before the start of authorization, because initial redux state is false for both of them.
Those are logs from router:
PrivateRoute.js:16 Loading: false isAuthenticated: false
PrivateRoute.js:16 Loading: true isAuthenticated: false
PrivateRoute.js:16 Loading: false isAuthenticated: true
It is working correctly, I just need a way to distinguish initial state from not authenticated user.
My attempt
- My first thought was changing initial state for isLoading to true:
Weird behavior. Page doesn't load at all. Even whole App component can't mount so I don't really know what is going on. - Changing initial state for isAuthenticated to null and changing conditions from
isLoading ?
to
isAuthenticated === null ?
(Router below)
Everything seems fine until PrivateRoute is required. When debugger is at the if statement everything freezes again.
This is my PrivateRoute component as I found Here
import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import Spinner from "../../components/Spinner";
const PrivateRoute = ({
component: Component,
isLoading,
isAuthenticated,
...rest
}) => (
<Route
{...rest}
render={props =>
isLoading ? (
<Spinner />
) : isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{ pathname: "/login", state: { from: props.location } }}
/>
)
}
/>
);
const mapStateToProps = state => ({
isLoading: state.auth.isLoading,
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps)(PrivateRoute);
isAuthenticatedin redux? Why are you trying to distinguish between initial state & not authenticated user? - displacedtexanisAuthenticatedandisLoadingcan be false at the same time - you have no choice but to redirect, so there's nothing logically wrong with that. (Also, might I suggestisAuthenticatingrather thanisLoadingto make it crystal clear what is happening). - Adam