Spaces:
Running
Running
File size: 1,129 Bytes
5a264f5 | 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 | import { createContext, useContext, useState, useEffect } from 'react'
import { api } from '../api/client'
const AuthContext = createContext(null)
export function AuthProvider({ children }) {
const [user, setUser] = useState(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
api.get('/api/auth/me')
.then(d => setUser(d.user))
.catch(() => setUser(null))
.finally(() => setLoading(false))
}, [])
async function login(identity, password) {
const d = await api.post('/api/auth/login', { email: identity, username: identity, password })
setUser(d.user)
return d.user
}
async function signup(username, email, password) {
const d = await api.post('/api/auth/signup', { username, email, password })
setUser(d.user)
return d.user
}
async function logout() {
await api.post('/api/auth/logout', {}).catch(() => {})
setUser(null)
}
return (
<AuthContext.Provider value={{ user, setUser, loading, login, signup, logout }}>
{children}
</AuthContext.Provider>
)
}
export const useAuth = () => useContext(AuthContext)
|