Skip to content

Commit e7992a4

Browse files
bug fix [chat]: Adds authentication loading state to prevent premature redirects on protected routes.
1 parent 6cf88b1 commit e7992a4

2 files changed

Lines changed: 16 additions & 5 deletions

File tree

client/src/context/AuthContext.tsx

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,23 @@ type AuthContextType = {
1313
login: (access: string, refresh: string) => void;
1414
logout: () => void;
1515
isLoggedIn: boolean;
16+
isLoading: boolean;
1617
};
1718

1819
const AuthContext = createContext<AuthContextType | undefined>(undefined);
1920

2021
export const AuthProvider = ({ children }: { children: ReactNode }) => {
2122
const [accessToken, setAccessToken] = useState<string | null>(null);
2223
const [refreshToken, setRefreshToken] = useState<string | null>(null);
24+
const [isLoading, setIsLoading] = useState(true);
2325
const router = useRouter();
2426

2527
useEffect(() => {
2628
const storedAccess = localStorage.getItem("accessToken");
2729
const storedRefresh = localStorage.getItem("refreshToken");
2830
if (storedAccess) setAccessToken(storedAccess);
2931
if (storedRefresh) setRefreshToken(storedRefresh);
32+
setIsLoading(false);
3033
}, []);
3134

3235
const login = (access: string, refresh: string) => {
@@ -48,7 +51,14 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
4851

4952
return (
5053
<AuthContext.Provider
51-
value={{ accessToken, refreshToken, login, logout, isLoggedIn }}
54+
value={{
55+
accessToken,
56+
refreshToken,
57+
login,
58+
logout,
59+
isLoggedIn,
60+
isLoading,
61+
}}
5262
>
5363
{children}
5464
</AuthContext.Provider>

client/src/pages/chat.tsx

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,16 @@ import Layout from "@/components/Layout";
55
import { useAuth } from "@/context/AuthContext";
66

77
export default function Chat() {
8-
const { isLoggedIn } = useAuth();
8+
const { isLoggedIn, isLoading } = useAuth();
99
const router = useRouter();
1010

1111
useEffect(() => {
12-
if (!isLoggedIn) {
12+
if (!isLoading && !isLoggedIn) {
1313
router.push("/login");
1414
}
15-
}, [isLoggedIn, router]);
15+
}, [isLoggedIn, isLoading, router]);
1616

17-
if (!isLoggedIn) return <p>Redirecting to login...</p>;
17+
if (isLoading) return <p>Loading...</p>;
18+
if (!isLoggedIn) return null;
1819
return <Layout>This is the chat page</Layout>;
1920
}

0 commit comments

Comments
 (0)