diff --git a/client/src/utils/SecureRoute.tsx b/client/src/utils/SecureRoute.tsx index df4eab9d28aa2c4eaffe55c993e4895532aae8ae..c8c238dffc4015a887fef707cf40b3eba5d6c6e5 100644 --- a/client/src/utils/SecureRoute.tsx +++ b/client/src/utils/SecureRoute.tsx @@ -11,11 +11,15 @@ interface SecureRouteProps extends RouteProps { /** Utility component to use for authentication, replace all routes that should be private with secure routes*/ const SecureRoute: React.FC<SecureRouteProps> = ({ login, component: Component, ...rest }: SecureRouteProps) => { const authenticated = useAppSelector((state) => state.user.authenticated) - const loading = useAppSelector((state) => state.user.loading) + const [initialized, setInitialized] = React.useState(false) useEffect(() => { - CheckAuthentication() + const waitForAuthentication = async () => { + await CheckAuthentication() + setInitialized(true) + } + waitForAuthentication() }, []) - if (!loading) { + if (initialized) { if (login) return ( <Route {...rest} render={(props) => (authenticated ? <Redirect to="/admin" /> : <Component {...props} />)} /> diff --git a/client/src/utils/checkAuthentication.ts b/client/src/utils/checkAuthentication.ts index 41294b14b0bde56468b1552bb83c36c23f75f772..7f41ef47086aa2531d80ff9d716f93179dca43b3 100644 --- a/client/src/utils/checkAuthentication.ts +++ b/client/src/utils/checkAuthentication.ts @@ -8,7 +8,7 @@ const UnAuthorized = () => { logoutUser()(store.dispatch) } -export const CheckAuthentication = () => { +export const CheckAuthentication = async () => { const authToken = localStorage.token if (authToken) { const decodedToken: any = jwtDecode(authToken) @@ -16,7 +16,7 @@ export const CheckAuthentication = () => { axios.defaults.headers.common['Authorization'] = authToken store.dispatch({ type: Types.LOADING_USER }) console.log('loading user') - axios + await axios .get('/users') .then((res) => { store.dispatch({ type: Types.SET_AUTHENTICATED })