mirror of
https://github.com/lemeow125/Borrowing-TrackerFrontend.git
synced 2025-09-17 04:59:35 +08:00
Added revalidation component to restore previous user sessions
This commit is contained in:
parent
139c0a3e3c
commit
f4468d4010
4 changed files with 103 additions and 20 deletions
39
src/Components/Revalidator/Revalidator.tsx
Normal file
39
src/Components/Revalidator/Revalidator.tsx
Normal file
|
@ -0,0 +1,39 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { JWTRefreshAPI, setAccessToken, setRefreshToken } from "../API/API";
|
||||
import { auth_toggle } from "../Plugins/Redux/Slices/AuthSlice/AuthSlice";
|
||||
import { RootState } from "../Plugins/Redux/Store/Store";
|
||||
|
||||
export default function Revalidator() {
|
||||
const dispatch = useDispatch();
|
||||
const navigate = useNavigate();
|
||||
const authenticated = useSelector((state: RootState) => state.auth.value);
|
||||
const [rechecked, setRechecked] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authenticated && rechecked) {
|
||||
navigate("/");
|
||||
console.log("Not logged in");
|
||||
}
|
||||
}, [authenticated, navigate, rechecked]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authenticated) {
|
||||
JWTRefreshAPI().then(async (response) => {
|
||||
if (response) {
|
||||
await dispatch(auth_toggle());
|
||||
navigate("/dashboard");
|
||||
console.log("User session restored");
|
||||
} else {
|
||||
await setRefreshToken("");
|
||||
await setAccessToken("");
|
||||
console.log("User session expired");
|
||||
}
|
||||
setRechecked(true);
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
return <></>;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue