feat: add API client and auth store

This commit is contained in:
2026-02-28 20:05:22 +01:00
parent b5c941c159
commit d0ee7d2f23
2 changed files with 96 additions and 0 deletions

View 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 }
}