From 95f44daef21b72171fe63ad2b4fb8440ebedd931 Mon Sep 17 00:00:00 2001 From: Alberto Defendi <1369-ahl-berto@users.noreply.gitlab.inf.unibz.it> Date: Sun, 16 May 2021 15:53:52 +0200 Subject: [PATCH] Call is_authenticated after role is fetched. --- src/api/PrivateRoute/PrivateRoute.tsx | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/api/PrivateRoute/PrivateRoute.tsx b/src/api/PrivateRoute/PrivateRoute.tsx index de89491..1736fc3 100644 --- a/src/api/PrivateRoute/PrivateRoute.tsx +++ b/src/api/PrivateRoute/PrivateRoute.tsx @@ -6,6 +6,7 @@ import { AuthContext } from 'components/AuthUser/AuthContext'; /** * A wrapper for <Route> that redirects to the login screen if you're not yet authenticated. + * Every non-public route must be wrapped with this component. * */ type Props = { @@ -31,17 +32,21 @@ export const PrivateRoute = ({ setLoading(true); return null; }; - fetch(); - }, []); + /* + Check if user is logged in. + Avoiding this condition would call is\_authenticated every time + this component state is triggered, falling in unnecessary calls to the + server. + */ + if (role) fetch(); + }, [auth]); const userHasRequiredRole = requiredRoles.includes(role); const message = userHasRequiredRole ? 'Please log in to view this page' : 'Your role is not allowed'; - return !loading ? ( - <p>loading</p> - ) : ( + return ( <Route exact={false} path={path} @@ -52,7 +57,7 @@ export const PrivateRoute = ({ <Redirect to={{ pathname: userHasRequiredRole - ? NonAuthRoutes.signIn + ? `auth/${NonAuthRoutes.signIn}` : NonAuthRoutes.unauthorized, state: { message, -- GitLab