-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathuseAuth.tsx
More file actions
72 lines (61 loc) · 1.77 KB
/
useAuth.tsx
File metadata and controls
72 lines (61 loc) · 1.77 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
import axios from "axios";
import { jwtDecode } from "jwt-decode";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
interface AuthContextType {
user: User | null;
authLoading: boolean;
refreshAuth: (quiet?: boolean) => void;
hasSignedUp: boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
}
export const AuthProvider = ({ children }: {
children: React.ReactNode
}) => {
const [user, setUser] = useState<User | null>(null);
const [authLoading, setAuthLoading] = useState(true);
const hasSignedUp = useMemo(() => {
if (!user) return false
if (!user.gender || !user.phoneNumber) return false
return true
}, [user])
const refreshAuth = async (quiet: boolean = false) => {
if (!quiet) setAuthLoading(true);
const accessToken = document.cookie.split(";").find((cookie) => cookie.trim().startsWith("access-token="))?.split("=")[1];
if (!accessToken) {
setUser(null);
setAuthLoading(false);
return;
}
try {
const payload = jwtDecode(accessToken) as any;
const userId = payload.userId as string;
if (!userId) throw new Error("Invalid token");
await axios.get("api/users/me")
.then(res => {
setUser(res.data.data)
})
} catch (err) {
console.error(err);
setUser(null);
} finally {
setAuthLoading(false);
}
}
useEffect(() => {
refreshAuth();
}, [])
return (
<AuthContext.Provider value={{
user, authLoading, refreshAuth, hasSignedUp
}}>
{children}
</AuthContext.Provider>
)
}