From 96b3936941714cf2d208701dda8b021356cbb338 Mon Sep 17 00:00:00 2001 From: ivamach Date: Sun, 14 Apr 2024 12:34:57 +0200 Subject: [PATCH] SMA-80: fixed PrivateRoute --- .../src/components/PrivateRoute.tsx | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/frontend/sportsmatch-app/src/components/PrivateRoute.tsx b/frontend/sportsmatch-app/src/components/PrivateRoute.tsx index 5468fa2e..0f8fb1a0 100644 --- a/frontend/sportsmatch-app/src/components/PrivateRoute.tsx +++ b/frontend/sportsmatch-app/src/components/PrivateRoute.tsx @@ -4,26 +4,33 @@ import { OpenAPI, ExSecuredEndpointService, ApiError } from '../generated/api' const PrivateRoute = () => { const requestedUrl = window.location.pathname - const [isLoggedIn, setLoggedIn] = useState(false) + const [isAuthorized, setAuthorized] = useState(true) + + useEffect(() => { + if (!localStorage.getItem('token')) { + setAuthorized(false) + } + },[]) useEffect(() => { const init = async () => { - OpenAPI.TOKEN = localStorage.getItem('token')! - try { - await ExSecuredEndpointService.getUserMainPage() - setLoggedIn(true) - } catch (error) { - const code = (error as ApiError).status - if (code === 401 || code === 403) { - localStorage.removeItem('token') - setLoggedIn(false) + if (localStorage.getItem('token')) { + OpenAPI.TOKEN = localStorage.getItem('token')! + try { + await ExSecuredEndpointService.getUserMainPage() + } catch (error) { + const code = (error as ApiError).status + if (code === 401 || code === 403) { + localStorage.removeItem('token') + setAuthorized(false) + } } } } init() }, []) - if (isLoggedIn) { + if (isAuthorized) { return } else { return