generated from muhtadeetaron/nextjs-template
feat(ui): add modal functionality, leaderboard view
This commit is contained in:
@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
|
||||
interface AuthContextType {
|
||||
token: string | null;
|
||||
@ -47,6 +47,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
const [token, setTokenState] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
// Custom setToken function that also updates cookies
|
||||
const setToken = (newToken: string | null) => {
|
||||
@ -58,21 +59,22 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
useEffect(() => {
|
||||
const initializeAuth = () => {
|
||||
const storedToken = getCookie("authToken");
|
||||
console.log("Current pathname:", pathname);
|
||||
console.log("Stored token:", storedToken);
|
||||
|
||||
if (storedToken) {
|
||||
setTokenState(storedToken);
|
||||
// Only redirect if we're on login/register pages
|
||||
if (
|
||||
router.pathname === "/" ||
|
||||
router.pathname === "/login" ||
|
||||
router.pathname === "/register"
|
||||
pathname === "/" ||
|
||||
pathname === "/login" ||
|
||||
pathname === "/register"
|
||||
) {
|
||||
console.log("Redirecting to /home");
|
||||
router.replace("/home");
|
||||
}
|
||||
} else {
|
||||
// Only redirect to login if we're on a protected page
|
||||
const publicPages = ["/", "/login", "/register"];
|
||||
if (!publicPages.includes(router.pathname)) {
|
||||
if (!publicPages.includes(pathname)) {
|
||||
router.replace("/");
|
||||
}
|
||||
}
|
||||
@ -80,10 +82,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
// Small delay to ensure router is ready
|
||||
const timer = setTimeout(initializeAuth, 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [router.pathname]);
|
||||
initializeAuth();
|
||||
}, [pathname, router]);
|
||||
|
||||
// Function to log out
|
||||
const logout = () => {
|
||||
|
||||
Reference in New Issue
Block a user