From 3bd38fdefad301547ecb6a58961b6a789b1163b0 Mon Sep 17 00:00:00 2001 From: Arnaud Fauconnet Date: Fri, 4 Nov 2022 23:06:11 +0100 Subject: [PATCH] fixed the loop when the token becomes invalid --- src/api/isTokenValid.ts | 3 ++- src/components/Login.tsx | 11 ++++++----- src/components/lib/AuthComponent.tsx | 15 ++++++++++----- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/api/isTokenValid.ts b/src/api/isTokenValid.ts index ba4209a..4be8a1e 100644 --- a/src/api/isTokenValid.ts +++ b/src/api/isTokenValid.ts @@ -30,5 +30,6 @@ export async function isTokenValid(token: ApiToken): Promise{ const errorCode: number = res.data.retrieveOrders.errorCode; - return (errorCode == API_INVALID_SHOP_ID_CODE); + return errorCode == API_INVALID_SHOP_ID_CODE; + // return false; } \ No newline at end of file diff --git a/src/components/Login.tsx b/src/components/Login.tsx index b810621..b613ec8 100644 --- a/src/components/Login.tsx +++ b/src/components/Login.tsx @@ -30,6 +30,12 @@ const schema = yup export function Login() { const user = useContext(userContext); const navigate = useNavigate(); + + useEffect(() => { + if (user.token) + navigate("/"); + }, [user.token]) + const { register, formState: { errors }, @@ -85,11 +91,6 @@ export function Login() { } } - useEffect(() => { - if (user.token) - navigate("/"); - }, [user.token]) - return (
diff --git a/src/components/lib/AuthComponent.tsx b/src/components/lib/AuthComponent.tsx index 11a2389..fa025e3 100644 --- a/src/components/lib/AuthComponent.tsx +++ b/src/components/lib/AuthComponent.tsx @@ -11,15 +11,20 @@ export function AuthComponent({ children }: AuthProps) { const navigate = useNavigate(); const user = useContext(userContext); - async function checkIfCustomerLogged(token: ApiToken){ - const isLogged: boolean = token != null && await isTokenValid(user.token); + async function checkIfCustomerLogged(token: ApiToken) { + const isLogged: boolean = await isTokenValid(user.token); - if (!isLogged){ - navigate("/login", { replace: true }); - } + if (!isLogged) { + user.setToken(null); + user.setId(null); + window.localStorage.removeItem("token"); + window.localStorage.removeItem("customerId"); + } } useEffect(() => { + if (!user.token) + navigate("/login", { replace: true }); // navigate needs to be wrapped in a useEffect so that it gets executed after the component is mounted. Otherwise it doesn't redirect checkIfCustomerLogged(user.token); }, [user.token])