router.replace seems to be causing infinite loop on application start, it appends the path from localhost:3000 to http://localhost:3000/dashboard and the application runs in infinite loop.
here’s the /page/index.js file of my project
export default function Home() {
const router = useRouter();
const routerQuery = useMemo(() => router.query, [router.query]);
// useLocalStorage Hook
const { handleGetStorage, handleSetStorage } = useEncryptedLocalStorage();
// Custom hook to handle encrypted local storage
const authenticationToken: string | null = handleGetStorage("token");
// const { getUserStatus } = usePermissions();
useEffect(() => {
const handleAccessToken = async () => {
if (!router.isReady) return;
const { access_token, unauthorized, refresh_token } = routerQuery;
if (unauthorized !== undefined) {
const errorMessage = encodeURIComponent(
"You are not Authorized, please try again",
);
router.push(`/login?unauthorized=${errorMessage}&loggedout`);
return;
}
switch (true) {
case !!access_token && !!refresh_token:
// Store the access token in local storage
handleSetStorage("token", access_token as string);
handleSetStorage("refresh_token", refresh_token as string);
// Redirect to dashboard if access_token is present
handleRegisterAuthenticated();
break;
case !access_token && !!authenticationToken:
// Redirect to dashboard if authentication token is present
handleRegisterAuthenticated();
break;
default:
// Redirect to login page if access_token is not present
handleUnAuthenticated();
}
};
// Call the function to handle access token
handleAccessToken();
const handleRegisterAuthenticated = async () => {
console.log("you're authenticated");
const dashboardType = "admin";
if (dashboardType === "admin") router.replace(superAdminPages[0].href);
else if (dashboardType === "business")
router.replace(businessManagerPages[0].href);
};
// //redirects unauthenticated users to the login page
const handleUnAuthenticated = async () => {
router.replace("/login");
};
return (
<div className="w-full h-screen flex justify-center items-center">
<Loader />
</div>
);
}
I have been stuck at this problem of infinite loop caused on application start, I have tried to narrow it down to index.js page itself. I have tried restructuring the code, I have removed the custom hook i was using which I suspected might be causing it, I have tried altering the useEffect hook in this page, removing and changing the dependency array. I have tried memoising the router.query object. But nothing seems to work so far.
Please take a look at the code and lemme know if I am missing something!
Thanks:)
Nisha Chauhan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.