forked from MergeFi/frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthContext.tsx
More file actions
80 lines (70 loc) · 1.93 KB
/
Copy pathAuthContext.tsx
File metadata and controls
80 lines (70 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useState,
} from "react";
import { getToken, setToken as persistToken, clearToken } from "@/lib/auth";
import { apiRequest } from "@/lib/api";
import type { AuthUser } from "@/types";
interface AuthContextValue {
user: AuthUser | null;
loading: boolean;
login: (token: string) => Promise<void>;
logout: () => void;
refresh: () => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<AuthUser | null>(null);
const [loading, setLoading] = useState(true);
const refresh = useCallback(async () => {
const token = getToken();
if (!token) {
setUser(null);
setLoading(false);
return;
}
try {
const session = await apiRequest<{ userId: string; username: string }>(
"/auth/me",
);
const profile = await apiRequest<AuthUser>(`/users/${session.userId}`);
setUser(profile);
} catch {
clearToken();
setUser(null);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
// Session hydration on mount: reads the JWT from localStorage and
// resolves the current user. Inherently async, not a render-time value.
// eslint-disable-next-line react-hooks/set-state-in-effect
void refresh();
}, [refresh]);
const login = useCallback(
async (token: string) => {
persistToken(token);
await refresh();
},
[refresh],
);
const logout = useCallback(() => {
clearToken();
setUser(null);
}, []);
return (
<AuthContext.Provider value={{ user, loading, login, logout, refresh }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error("useAuth must be used within an AuthProvider");
return ctx;
}