feat: add API client and auth store
This commit is contained in:
39
frontend/src/store/auth.ts
Normal file
39
frontend/src/store/auth.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { authApi } from '../api'
|
||||
|
||||
export interface User {
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
// Simple module-level state (no external lib needed)
|
||||
let currentUser: User | null = null
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
export function useAuth() {
|
||||
const [user, setUser] = useState<User | null>(currentUser)
|
||||
const [loading, setLoading] = useState(currentUser === null)
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => setUser(currentUser)
|
||||
listeners.add(update)
|
||||
if (currentUser === null) {
|
||||
authApi.me()
|
||||
.then((res) => { currentUser = res.data; listeners.forEach((l) => l()) })
|
||||
.catch(() => { currentUser = null; listeners.forEach((l) => l()) })
|
||||
.finally(() => setLoading(false))
|
||||
}
|
||||
return () => { listeners.delete(update) }
|
||||
}, [])
|
||||
|
||||
const logout = async () => {
|
||||
await authApi.logout()
|
||||
currentUser = null
|
||||
listeners.forEach((l) => l())
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
return { user, loading, logout }
|
||||
}
|
||||
Reference in New Issue
Block a user