Skip to content

Commit 42d3384

Browse files
committed
Enhance AuthContext initialization logic to handle user data retrieval from localStorage, improving user session management and routing behavior.
1 parent fd5f6f3 commit 42d3384

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

frontend/src/context/AuthContext.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,31 @@ const AuthProvider = ({ children }) => {
144144
};
145145

146146
const initAuth = () => {
147+
const storedUserData = localStorage.getItem(authConfig.userDataName);
148+
147149
if (["/login", "/register"].includes(router.pathname)) {
150+
if (storedUserData) {
151+
try {
152+
const userData = JSON.parse(storedUserData);
153+
setUser(userData);
154+
setLoading(false);
155+
setIsInitialized(true);
156+
router.push("/");
157+
} catch (error) {
158+
localStorage.removeItem(authConfig.userDataName);
159+
setLoading(false);
160+
setIsInitialized(true);
161+
}
162+
} else {
163+
setLoading(false);
164+
setIsInitialized(true);
165+
}
166+
return;
167+
}
168+
169+
if (!storedUserData) {
170+
setLoading(false);
171+
setIsInitialized(true);
148172
return;
149173
}
150174

@@ -234,7 +258,7 @@ const AuthProvider = ({ children }) => {
234258

235259
useEffect(() => {
236260
initAuth();
237-
}, []);
261+
}, [router.pathname]);
238262

239263
const values = {
240264
user,

0 commit comments

Comments
 (0)