fixed the loop when the token becomes invalid

This commit is contained in:
Arnaud Fauconnet 2022-11-04 23:06:11 +01:00
parent 2e9db61173
commit 3bd38fdefa
3 changed files with 18 additions and 11 deletions

View File

@ -30,5 +30,6 @@ export async function isTokenValid(token: ApiToken): Promise<boolean>{
const errorCode: number = res.data.retrieveOrders.errorCode;
return (errorCode == API_INVALID_SHOP_ID_CODE);
return errorCode == API_INVALID_SHOP_ID_CODE;
// return false;
}

View File

@ -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 (
<main className="cardContainer">
<form onSubmit={handleSubmit(onSubmit)}>

View File

@ -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])