-
Notifications
You must be signed in to change notification settings - Fork 19
/
auth.tsx
47 lines (39 loc) · 1.23 KB
/
auth.tsx
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
import { createContext, useContext, useMemo, useState } from 'react'
import { storage } from '@/utils'
type User = { email: string }
type AuthContext = {
token: string
user?: User
login: (email: string) => void
logout: () => void
}
const AuthContext = createContext<AuthContext | null>(null)
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
const [token, setToken] = useState<string>(() => storage.get('token') || '')
const [user, setUser] = useState<AuthContext['user']>(() => storage.get('user') || undefined)
const value = useMemo(
() => ({
token,
user,
login: (email: string) => {
setToken('token')
setUser({ email })
storage.set('token', 'a0731ae631bc01dea99f13b3f8ed48fc')
storage.set('user', { email })
},
logout: () => {
setToken('')
setUser(undefined)
storage.remove('token')
storage.remove('user')
},
}),
[token, user],
)
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
export const useAuth = (): AuthContext => {
const context = useContext(AuthContext)
if (!context) throw Error('useAuth should be used within <AuthProvider />')
return context
}